package com.quanquan.store.service;

import DTO.PageDTO;
import DTO.image.Image;
import DTO.image.ImageDTO;
import DTO.user.UserInfoDTO;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.quanquan.store.configBean.RabbitSender;
import com.quanquan.store.dao.AbstractBatchDao;
import com.quanquan.store.dto.CouponCodeDTO;
import com.quanquan.store.dto.CouponDTO;
import com.quanquan.store.dto.IdDTO;
import com.quanquan.store.dto.PaymentRechargeDTO;
import com.quanquan.store.entity.*;
import com.quanquan.store.repository.*;
import com.quanquan.store.request.*;
import commond.ImageOutPut;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cglib.core.internal.Function;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import utils.*;

import javax.persistence.criteria.Predicate;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @ClassName:CouponService
 * @Description:TODO
 * @Author:xiongjunbao
 * @Date:2019/3/18 14:58
 * @Version 1.0
 */
@Service
public class CouponService extends AbstractBatchDao {

    @Value("${module-url.parkingUrl}")
    private String parkingUrl;
    @Value("${module-url.userUrl}")
    private String userUrl;

    private final CouponRepository couponRepository;
    private final CouponCodeRepository couponCodeRepository;
    private final StoreCouponRepository storeCouponRepository;
    private final StoreCouponService storeCouponService;
    private final AmqpTemplate amqpTemplate;
    private final RestTemplate restTemplate;
    private final HistoryService historyService;
    private final CouponHistoryRepository couponHistoryRepository;
    private final RabbitSender rabbitSender;
    private final AdminRepository adminRepository;
    private final CouponCommercialRepository couponCommercialRepository;
    private final StoreRepository storeRepository;
    private final StoreCommercialRepository storeCommercialRepository;
    private final ShopMallRepository shopMallRepository;
    private final SendCouponRecordRepository sendCouponRecordRepository;


    @Autowired
    public CouponService(CouponRepository couponRepository, CouponCodeRepository couponCodeRepository, StoreCouponRepository storeCouponRepository, StoreCouponService storeCouponService, AmqpTemplate amqpTemplate, RestTemplate restTemplate, HistoryService historyService, CouponHistoryRepository couponHistoryRepository, AdminRepository adminRepository, RabbitSender rabbitSender, CouponCommercialRepository couponCommercialRepository, StoreRepository storeRepository, StoreCommercialRepository storeCommercialRepository, ShopMallRepository shopMallRepository, SendCouponRecordRepository sendCouponRecordRepository) {
        this.couponRepository = couponRepository;
        this.couponCodeRepository = couponCodeRepository;
        this.storeCouponRepository = storeCouponRepository;
        this.storeCouponService = storeCouponService;
        this.amqpTemplate = amqpTemplate;
        this.restTemplate = restTemplate;
        this.historyService = historyService;
        this.couponHistoryRepository = couponHistoryRepository;
        this.adminRepository = adminRepository;
        this.rabbitSender = rabbitSender;
        this.couponCommercialRepository = couponCommercialRepository;
        this.storeRepository = storeRepository;
        this.storeCommercialRepository = storeCommercialRepository;
        this.shopMallRepository = shopMallRepository;
        this.sendCouponRecordRepository = sendCouponRecordRepository;
    }

    /**
     * 生成优惠券及其券码
     *
     * @param request
     * @return
     */
    @Transactional
    public boolean saveCoupon1(CouponRequest request) {
        Date date = new Date();
        //生成券模板
        Coupon coupon = new Coupon();
        BeanUtil.copyProperties(request, coupon, true, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        coupon.setId(UUIDGenerator.getUUID());
        if (StringUtil.isNotEmpty(request.getUseTimeStart())) {
            coupon.setUseTimeStart(DateUtils.dateToString(DateUtils.strToDate(request.getUseTimeStart() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
        }
        if (StringUtil.isNotEmpty(request.getUseTimeEnd())) {
            coupon.setUseTimeEnd(DateUtils.dateToString(DateUtils.strToDate(request.getUseTimeEnd() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
        }
        coupon.setBuyTimeStart(DateUtils.dateToString(DateUtils.strToDate(request.getBuyTimeStart() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
        coupon.setBuyTimeEnd(DateUtils.dateToString(DateUtils.strToDate(request.getBuyTimeEnd() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
        coupon.setShowTimeStart(DateUtils.dateToString(DateUtils.strToDate(request.getShowTimeStart() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
        coupon.setShowTimeEnd(DateUtils.dateToString(DateUtils.strToDate(request.getShowTimeEnd() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
        coupon.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
        if (null == request.getRemainTotal()) {
            coupon.setRemainTotal(request.getSumTatal());
        }
        //绑定商户
        if (request.getStoreIdList() != null) {
            for (String storeId : request.getStoreIdList()) {
                StoreCoupon storeCoupon = new StoreCoupon();
                storeCoupon.setId(UUIDGenerator.getUUID());
                storeCoupon.setCouponId(coupon.getId());
                storeCoupon.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                if (coupon.getStatus() == 1) {
                    storeCoupon.setStatusShow(0);
                } else {
                    storeCoupon.setStatusShow(1);
                }
                storeCoupon.setStatusRemove(0);
                storeCoupon.setStoreId(storeId);
                storeCouponRepository.saveAndFlush(storeCoupon);
            }
        }
        //绑定业态
        if (request.getCommercialIdList() != null) {
            for (String commercialId : request.getCommercialIdList()) {
                CouponCommercial couponCommercial = new CouponCommercial();
                couponCommercial.setId(UUIDGenerator.getUUID());
                couponCommercial.setCouponId(coupon.getId());
                couponCommercial.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                couponCommercial.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                if (coupon.getStatus() == 1) {
                    couponCommercial.setStatusShow(0);
                } else {
                    couponCommercial.setStatusShow(1);
                }
                couponCommercial.setStatusRemove(0);
                couponCommercial.setCommercialId(commercialId);
                couponCommercialRepository.saveAndFlush(couponCommercial);
            }
        }
        String useEnd = null;
        if (request.getUseTimeType() == 1) {
            useEnd = coupon.getUseTimeEnd();
        }
        if (request.getUseTimeType() == 2) {
            useEnd = DateUtils.dateToString(DateUtils.getDateAfterHour(request.getUseTimeHour()), DateUtils.TIMESTAMP);
        }
        if (request.getUseTimeType() == 3) {
            useEnd = DateUtils.dateToString(DateUtils.getEndOfDay(date), DateUtils.TIMESTAMP);
        }
        //生成对应券
        if (null != request.getSumType() && request.getSumType() == 1) {
            System.out.println("不限量券");
        } else {
            List<CouponCode> couponCodes = new LinkedList<>();
            for (int i = 0; i < request.getSumTatal(); i++) {
                CouponCode couponCode = new CouponCode();
                couponCode.setId(UUIDGenerator.getUUID());
                couponCode.setCouponCode(DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.getRandomStr());
                couponCode.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                couponCode.setCouponId(coupon.getId());
                couponCode.setType(coupon.getType());
                couponCode.setStatus(-1);
                couponCode.setUseTimeEnd(useEnd);
                couponCode.setCouponName(request.getName());
                couponCode.setUseTimeStart(coupon.getUseTimeStart());
                couponCodes.add(couponCode);
            }
            batchInsert(couponCodes);
        }
        bandingImageShip(coupon.getId(), request.getImageIds());
        couponRepository.saveAndFlush(coupon);
        return true;
    }

    /**
     * 生成优惠券及其券码
     *
     * @param request
     * @return
     */
    @Transactional
    public boolean saveCoupon(CouponRequest request) {
        Date date = new Date();
        //生成券模板
        Coupon coupon = new Coupon();
        BeanUtil.copyProperties(request, coupon, true, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        coupon.setId(UUIDGenerator.getUUID());
        if (StringUtil.isNotEmpty(request.getUseTimeStart())) {
            coupon.setUseTimeStart(DateUtils.dateToString(DateUtils.strToDate(request.getUseTimeStart() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
        }
        if (StringUtil.isNotEmpty(request.getUseTimeEnd())) {
            coupon.setUseTimeEnd(DateUtils.dateToString(DateUtils.strToDate(request.getUseTimeEnd() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
        }
        coupon.setBuyTimeStart(DateUtils.dateToString(DateUtils.strToDate(request.getBuyTimeStart() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
        coupon.setBuyTimeEnd(DateUtils.dateToString(DateUtils.strToDate(request.getBuyTimeEnd() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
        coupon.setShowTimeStart(DateUtils.dateToString(DateUtils.strToDate(request.getShowTimeStart() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
        coupon.setShowTimeEnd(DateUtils.dateToString(DateUtils.strToDate(request.getShowTimeEnd() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
        coupon.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
        if (null == request.getRemainTotal()) {
            coupon.setRemainTotal(request.getSumTatal());
        }
        //绑定商户
        if (request.getStoreIdList() != null) {
            for (String storeId : request.getStoreIdList()) {
                StoreCoupon storeCoupon = new StoreCoupon();
                storeCoupon.setId(UUIDGenerator.getUUID());
                storeCoupon.setCouponId(coupon.getId());
                storeCoupon.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                if (coupon.getStatus() == 1) {
                    storeCoupon.setStatusShow(0);
                } else {
                    storeCoupon.setStatusShow(1);
                }
                storeCoupon.setStatusRemove(0);
                storeCoupon.setStoreId(storeId);
                storeCouponRepository.saveAndFlush(storeCoupon);
            }
        }
        //绑定业态
        if (request.getCommercialIdList() != null) {
            for (String commercialId : request.getCommercialIdList()) {
                CouponCommercial couponCommercial = new CouponCommercial();
                couponCommercial.setId(UUIDGenerator.getUUID());
                couponCommercial.setCouponId(coupon.getId());
                couponCommercial.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                couponCommercial.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                if (coupon.getStatus() == 1) {
                    couponCommercial.setStatusShow(0);
                } else {
                    couponCommercial.setStatusShow(1);
                }
                couponCommercial.setStatusRemove(0);
                couponCommercial.setCommercialId(commercialId);
                couponCommercialRepository.saveAndFlush(couponCommercial);
            }
        }
        String useEnd = null;
        if (request.getUseTimeType() == 1) {
            useEnd = coupon.getUseTimeEnd();
        }
        if (request.getUseTimeType() == 2) {
            useEnd = DateUtils.dateToString(DateUtils.getDateAfterHour(request.getUseTimeHour()), DateUtils.TIMESTAMP);
        }
        if (request.getUseTimeType() == 3) {
            useEnd = DateUtils.dateToString(DateUtils.getEndOfDay(date), DateUtils.TIMESTAMP);
        }
        //生成对应券
        if (null != request.getSumType() && request.getSumType() == 1) {
            System.out.println("不限量券");
        } else {
            List<CouponCode> couponCodes = new LinkedList<>();
            for (int i = 0; i < request.getSumTatal(); i++) {
                CouponCode couponCode = new CouponCode();
                couponCode.setId(UUIDGenerator.getUUID());
                couponCode.setCouponCode(DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.getRandomStr());
                couponCode.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                couponCode.setCouponId(coupon.getId());
                couponCode.setType(coupon.getType());
                couponCode.setStatus(-1);
                couponCode.setUseTimeEnd(useEnd);
                couponCode.setCouponName(request.getName());
                couponCode.setUseTimeStart(coupon.getUseTimeStart());
                couponCodes.add(couponCode);
            }
            batchInsert(couponCodes);
        }
        bandingImageShip(coupon.getId(), request.getImageIds());
        couponRepository.saveAndFlush(coupon);
        return true;
    }

    /**
     * 更新券信息
     *
     * @param request
     * @return
     */
    @Transactional
    public boolean updateCoupon1(CouponRequest request) {
        Date date = new Date();
        Coupon coupon = couponRepository.findByCouponIdAndStatus(request.getId());
        if (coupon != null) {
            //如果券未下架，不可修改券信息
            if (coupon.getStatus() == 1) {
                return false;
            }
            //绑定业态
            if (request.getCommercialIdList() != null) {
                List<CouponCommercial> couponCommercials = couponCommercialRepository.findByCouponIdAndStatus(coupon.getId());
                for (CouponCommercial couponCommercial : couponCommercials) {
                    couponCommercial.setStatusRemove(1);
                    couponCommercialRepository.saveAndFlush(couponCommercial);
                }
                for (String commercialId : request.getCommercialIdList()) {
                    CouponCommercial couponCommercial = new CouponCommercial();
                    couponCommercial.setId(UUIDGenerator.getUUID());
                    couponCommercial.setCouponId(coupon.getId());
                    couponCommercial.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    couponCommercial.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    if (coupon.getStatus() == 1) {
                        couponCommercial.setStatusShow(0);
                    } else {
                        couponCommercial.setStatusShow(1);
                    }
                    couponCommercial.setStatusRemove(0);
                    couponCommercial.setCommercialId(commercialId);
                    couponCommercialRepository.saveAndFlush(couponCommercial);
                }
            }
            //绑定商户
            if (request.getStoreIdList() != null) {
                List<StoreCoupon> storeCouponList = storeCouponRepository.findByCouponId1(coupon.getId());
                for (StoreCoupon storeCoupon : storeCouponList) {
                    storeCoupon.setStatusRemove(1);
                    storeCouponRepository.saveAndFlush(storeCoupon);
                }
                for (String storeId : request.getStoreIdList()) {
                    StoreCoupon storeCoupon = new StoreCoupon();
                    storeCoupon.setId(UUIDGenerator.getUUID());
                    storeCoupon.setCouponId(coupon.getId());
                    storeCoupon.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    if (coupon.getStatus() == 1) {
                        storeCoupon.setStatusShow(0);
                    } else {
                        storeCoupon.setStatusShow(1);
                    }
                    storeCoupon.setStatusRemove(0);
                    storeCoupon.setStoreId(storeId);
                    storeCouponRepository.saveAndFlush(storeCoupon);
                }
            }
            String useEnd = null;
            if (request.getUseTimeType() == 1) {
                useEnd = coupon.getUseTimeEnd();
            }
            if (request.getUseTimeType() == 2) {
                useEnd = DateUtils.dateToString(DateUtils.getDateAfterHour(request.getUseTimeHour()), DateUtils.TIMESTAMP);
            }
            if (request.getUseTimeType() == 3) {
                useEnd = DateUtils.dateToString(DateUtils.getEndOfDay(date), DateUtils.TIMESTAMP);
            }
            List<CouponCode> couponCodes = new ArrayList<>();
            //修改券库存，在原来的基础上添加或者减去券
            int sumTotal = 0;
            //如果传入的是不限制的券，将所有券设置为失效状态
            if (Integer.valueOf(1).equals(request.getSumType())) {
                coupon.setSumTatal(0);
                coupon.setRemainTotal(0);
                List<CouponCode> couponCodeList = couponCodeRepository.queryByCouponIdAndUseEnd(coupon.getId());
                for (CouponCode couponCode : couponCodeList) {
                    //设置为失效状态
                    couponCode.setStatus(-2);
                    couponCodes.add(couponCode);
                }
            } else {
                if (coupon.getRemainTotal() == null) {
                    sumTotal = request.getSumTatal();
                    coupon.setSumTatal(request.getSumTatal());
                    coupon.setRemainTotal(request.getSumTatal());
                    //修改券码表对应券
                    for (int i = 0; i < sumTotal; i++) {
                        CouponCode couponCode = new CouponCode();
                        couponCode.setId(UUIDGenerator.getUUID());
                        couponCode.setCouponCode(DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.getRandomStr());
                        couponCode.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                        couponCode.setCouponId(coupon.getId());
                        couponCode.setStatus(-1);
                        couponCode.setType(request.getType());
                        couponCode.setCouponName(request.getName());
                        couponCode.setUseTimeEnd(useEnd);
                        couponCode.setUseTimeStart(coupon.getUseTimeStart());
                        couponCodes.add(couponCode);
                    }
                } else {
                    if (request.getSumTatal() > coupon.getRemainTotal()) {
                        sumTotal = request.getSumTatal() - coupon.getRemainTotal();
                        coupon.setSumTatal(request.getSumTatal());
                        coupon.setRemainTotal(request.getSumTatal());
                        //修改券码表对应券
                        for (int i = 0; i < sumTotal; i++) {
                            CouponCode couponCode = new CouponCode();
                            couponCode.setId(UUIDGenerator.getUUID());
                            couponCode.setCouponCode(DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.getRandomStr());
                            couponCode.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                            couponCode.setCouponId(coupon.getId());
                            couponCode.setStatus(-1);
                            couponCode.setType(request.getType());
                            couponCode.setCouponName(request.getName());
                            couponCode.setUseTimeEnd(useEnd);
                            couponCode.setUseTimeStart(coupon.getUseTimeStart());
                            couponCodes.add(couponCode);
                        }
                    } else if (request.getSumTatal() < coupon.getRemainTotal()) {
                        sumTotal = coupon.getRemainTotal() - request.getSumTatal();
                        coupon.setSumTatal(request.getSumTatal());
                        coupon.setRemainTotal(request.getSumTatal());
                        //修改券码表对应券
                        List<CouponCode> couponCodeList = couponCodeRepository.queryByCouponIdAndUseEnd(coupon.getId());
                        for (int i = 0; i < sumTotal; i++) {
                            CouponCode couponCode = couponCodeList.get(i);
                            //设置为失效状态
                            couponCode.setStatus(-2);
                            couponCodes.add(couponCode);
                        }
                    }
                }
            }
            //更新信息
            coupon.setName(request.getName());
            coupon.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
            coupon.setType(request.getType());
            coupon.setCouponDesc(request.getCouponDesc());
            coupon.setDisType(request.getDisType());
            coupon.setUseTimeType(request.getUseTimeType());
            coupon.setUseTimeHour(request.getUseTimeHour());
            coupon.setSumType(request.getSumType());
            coupon.setStatus(request.getStatus());
            coupon.setStatusShow(request.getStatusShow());
            coupon.setValueType(request.getValueType());
            coupon.setIntegral(request.getIntegral());
            coupon.setPrice(request.getPrice());
            coupon.setUseRule(request.getUseRule());
            coupon.setStatusHot(request.getStatusHot());
            coupon.setBindType(request.getBindType());
            if (StringUtil.isNotEmpty(request.getUseTimeStart())) {
                coupon.setUseTimeStart(DateUtils.dateToString(DateUtils.strToDate(request.getUseTimeStart() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
            }
            if (StringUtil.isNotEmpty(request.getUseTimeEnd())) {
                coupon.setUseTimeEnd(DateUtils.dateToString(DateUtils.strToDate(request.getUseTimeEnd() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
            }
            coupon.setBuyTimeStart(DateUtils.dateToString(DateUtils.strToDate(request.getBuyTimeStart() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
            coupon.setBuyTimeEnd(DateUtils.dateToString(DateUtils.strToDate(request.getBuyTimeEnd() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
            coupon.setBuyTimeCount(request.getBuyTimeCount());
            coupon.setShowTimeStart(DateUtils.dateToString(DateUtils.strToDate(request.getShowTimeStart() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
            coupon.setShowTimeEnd(DateUtils.dateToString(DateUtils.strToDate(request.getShowTimeEnd() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
            coupon.setCount(request.getCount());
            batchInsert(couponCodes);
            bandingImageShip(coupon.getId(), request.getImageIds());
            System.out.println(coupon);
            couponRepository.saveAndFlush(coupon);
            return true;
        }
        return false;
    }

    /**
     * 更新券信息(新)
     *
     * @param request
     * @return
     */
    @Transactional
    public boolean updateCoupon(CouponRequest request) {
        Date date = new Date();
        Coupon coupon = couponRepository.findByCouponIdAndStatus(request.getId());
        if (coupon != null) {
            //绑定业态
            if (request.getBindType() == 2) {
                //删除原先绑定的商户和业态
                List<CouponCommercial> couponCommercials = couponCommercialRepository.findByCouponIdAndStatus(coupon.getId());
                for (CouponCommercial couponCommercial : couponCommercials) {
                    couponCommercial.setStatusRemove(1);
                    couponCommercialRepository.saveAndFlush(couponCommercial);
                }
                if (request.getCommercialIdList() != null) {
                    List<StoreCoupon> storeCouponList = storeCouponRepository.findByCouponId1(coupon.getId());
                    for (StoreCoupon storeCoupon : storeCouponList) {
                        storeCoupon.setStatusRemove(1);
                        storeCouponRepository.saveAndFlush(storeCoupon);
                    }
                    for (String commercialId : request.getCommercialIdList()) {
                        CouponCommercial couponCommercial = new CouponCommercial();
                        couponCommercial.setId(UUIDGenerator.getUUID());
                        couponCommercial.setCouponId(coupon.getId());
                        couponCommercial.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                        couponCommercial.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                        if (coupon.getStatus() == 1) {
                            couponCommercial.setStatusShow(0);
                        } else {
                            couponCommercial.setStatusShow(1);
                        }
                        couponCommercial.setStatusRemove(0);
                        couponCommercial.setCommercialId(commercialId);
                        couponCommercialRepository.saveAndFlush(couponCommercial);
                    }
                }
            }
            //绑定商户
            if (request.getBindType() == 1) {
                //删除原先绑定的商户和业态
                List<CouponCommercial> couponCommercials = couponCommercialRepository.findByCouponIdAndStatus(coupon.getId());
                for (CouponCommercial couponCommercial : couponCommercials) {
                    couponCommercial.setStatusRemove(1);
                    couponCommercialRepository.saveAndFlush(couponCommercial);
                }
                if (request.getStoreIdList() != null) {
                    List<StoreCoupon> storeCouponList = storeCouponRepository.findByCouponId1(coupon.getId());
                    for (StoreCoupon storeCoupon : storeCouponList) {
                        storeCoupon.setStatusRemove(1);
                        storeCouponRepository.saveAndFlush(storeCoupon);
                    }
                    for (String storeId : request.getStoreIdList()) {
                        StoreCoupon storeCoupon = new StoreCoupon();
                        storeCoupon.setId(UUIDGenerator.getUUID());
                        storeCoupon.setCouponId(coupon.getId());
                        storeCoupon.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                        if (coupon.getStatus() == 1) {
                            storeCoupon.setStatusShow(0);
                        } else {
                            storeCoupon.setStatusShow(1);
                        }
                        storeCoupon.setStatusRemove(0);
                        storeCoupon.setStoreId(storeId);
                        storeCouponRepository.saveAndFlush(storeCoupon);
                    }
                }

            }
            String useEnd = null;
            if (request.getUseTimeType() == 1) {
                useEnd = coupon.getUseTimeEnd();
            }
            if (request.getUseTimeType() == 2) {
                useEnd = DateUtils.dateToString(DateUtils.getDateAfterHour(request.getUseTimeHour()), DateUtils.TIMESTAMP);
            }
            if (request.getUseTimeType() == 3) {
                useEnd = DateUtils.dateToString(DateUtils.getEndOfDay(date), DateUtils.TIMESTAMP);
            }
            List<CouponCode> couponCodes = new ArrayList<>();
            //修改券库存，在原来的基础上添加或者减去券
            int total = 0;
            //如果传入的是不限制的券，将所有券设置为失效状态
            if (Integer.valueOf(1).equals(request.getSumType())) {
                coupon.setRemainTotal(0);
                coupon.setSumTatal(0);
                List<CouponCode> couponCodeList = couponCodeRepository.queryByCouponIdAndUseEnd(coupon.getId());
                for (CouponCode couponCode : couponCodeList) {
                    //设置为失效状态
                    couponCode.setStatus(-2);
                    couponCodes.add(couponCode);
                }
            } else {
                //如果是第一次从无限库存修正为有限库存
                if (coupon.getRemainTotal() == null) {
                    total = request.getSumTatal();
                    coupon.setRemainTotal(total);
                    coupon.setSumTatal(total);
                    //修改券码表对应券
                    for (int i = 0; i < total; i++) {
                        CouponCode couponCode = new CouponCode();
                        couponCode.setId(UUIDGenerator.getUUID());
                        couponCode.setCouponCode(DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.getRandomStr());
                        couponCode.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                        couponCode.setCouponId(coupon.getId());
                        couponCode.setStatus(-1);
                        couponCode.setType(request.getType());
                        couponCode.setCouponName(request.getName());
                        couponCode.setUseTimeEnd(useEnd);
                        couponCode.setUseTimeStart(coupon.getUseTimeStart());
                        couponCodes.add(couponCode);
                    }
                } else {
                    //当想要调整的库存大于原本券的库存时
                    if (request.getSumTatal() > coupon.getSumTatal()) {
                        total = request.getSumTatal() - coupon.getSumTatal();
                        //加上多的库存
                        coupon.setRemainTotal(coupon.getRemainTotal() + total);
                        coupon.setSumTatal(coupon.getSumTatal() + total);
                        //修改券码表对应券
                        for (int i = 0; i < total; i++) {
                            CouponCode couponCode = new CouponCode();
                            couponCode.setId(UUIDGenerator.getUUID());
                            couponCode.setCouponCode(DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.getRandomStr());
                            couponCode.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                            couponCode.setCouponId(coupon.getId());
                            couponCode.setStatus(-1);
                            couponCode.setType(request.getType());
                            couponCode.setCouponName(request.getName());
                            couponCode.setUseTimeEnd(useEnd);
                            couponCode.setUseTimeStart(coupon.getUseTimeStart());
                            couponCodes.add(couponCode);
                        }
                        //当想要调整的库存小于原本券的库存时
                    } else if (request.getSumTatal() < coupon.getSumTatal()) {
                        total = coupon.getSumTatal() - request.getSumTatal();
                        //减掉多的库存
                        coupon.setRemainTotal(coupon.getRemainTotal() - total);
                        coupon.setSumTatal(coupon.getSumTatal() - total);
                        //修改券码表对应券
                        List<CouponCode> couponCodeList = couponCodeRepository.queryByCouponIdAndUseEnd(coupon.getId());
                        for (int i = 0; i < total; i++) {
                            CouponCode couponCode = couponCodeList.get(i);
                            //设置为失效状态
                            couponCode.setStatus(-2);
                            couponCodes.add(couponCode);
                        }
                    } else {
                        System.out.println("库存不变");
                    }
                }
            }
            //更新信息
            coupon.setName(request.getName());
            coupon.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
            coupon.setType(request.getType());
            coupon.setCouponDesc(request.getCouponDesc());
            coupon.setDisType(request.getDisType());
            coupon.setUseTimeType(request.getUseTimeType());
            coupon.setUseTimeHour(request.getUseTimeHour());
            coupon.setSumType(request.getSumType());
            coupon.setStatus(0);
            coupon.setUseRule(request.getUseRule());
            coupon.setStatusHot(request.getStatusHot());
            coupon.setBindType(request.getBindType());
            if (StringUtil.isNotEmpty(request.getUseTimeStart())) {
                coupon.setUseTimeStart(DateUtils.dateToString(DateUtils.strToDate(request.getUseTimeStart() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
            }
            if (StringUtil.isNotEmpty(request.getUseTimeEnd())) {
                coupon.setUseTimeEnd(DateUtils.dateToString(DateUtils.strToDate(request.getUseTimeEnd() + ":00", DateUtils.TIMESTAMP), DateUtils.TIMESTAMP));
            }
            batchInsert(couponCodes);
            bandingImageShip(coupon.getId(), request.getImageIds());
            System.out.println(coupon);
            couponRepository.saveAndFlush(coupon);
            return true;
        }
        return false;
    }

    /**
     * 绑定商户图片
     *
     * @param couponId
     * @param imageIdList
     */
    private void bandingImageShip(String couponId, List<String> imageIdList) {
        ImageOutPut imageOutPut = new ImageOutPut();
        imageOutPut.setForeignKeyId(couponId);
        imageOutPut.setImageSource("coupon");
        //通过mq消息队列发送给资源模块绑定图片关系
//        amqpTemplate.convertAndSend("image.exchange", "image.store", JsonUtil.toJson(imageOutPut));
        Map<String, Object> properties = new HashMap<>();
        properties.put("imageIds", imageIdList);

        String exchange = "image.exchange";
        String routingKey = "image.store";

        rabbitSender.sendMessageToMQ(imageOutPut, properties, exchange, routingKey);
    }

    /**
     * 下架/上架优惠券
     *
     * @param request
     * @return
     */
    public String changeCouponStatus(CouponRequest request) {
        Coupon coupon = couponRepository.findByCouponId(request.getId());
        if (request.getStatus() == 0) {
            coupon.setStatus(1);
            List<StoreCoupon> storeCoupons = storeCouponRepository.findByCouponId1(coupon.getId());
            for (StoreCoupon storeCoupon : storeCoupons) {
                storeCoupon.setStatusShow(0);
                storeCouponRepository.saveAndFlush(storeCoupon);
            }
            List<CouponCommercial> couponCommercials = couponCommercialRepository.findByCouponIdAndStatus(coupon.getId());
            for (CouponCommercial couponCommercial : couponCommercials) {
                couponCommercial.setStatusShow(0);
                couponCommercialRepository.saveAndFlush(couponCommercial);
            }
            couponRepository.saveAndFlush(coupon);
            return "上架成功";
        }
        coupon.setStatus(0);
        List<StoreCoupon> storeCoupons = storeCouponRepository.findByCouponId1(coupon.getId());
        for (StoreCoupon storeCoupon : storeCoupons) {
            storeCoupon.setStatusShow(1);
            storeCouponRepository.saveAndFlush(storeCoupon);
        }
        List<CouponCommercial> couponCommercials = couponCommercialRepository.findByCouponIdAndStatus(coupon.getId());
        for (CouponCommercial couponCommercial : couponCommercials) {
            couponCommercial.setStatusShow(1);
            couponCommercialRepository.saveAndFlush(couponCommercial);
        }
        couponRepository.saveAndFlush(coupon);
        return "下架成功";
    }

    /**
     * 查找商户对应优惠券
     *
     * @param storeId
     * @return
     */
    public List<Coupon> queryByStoreId(String storeId, Integer page, Integer size) {
        Date date = new Date();
        List<Coupon> couponList = new LinkedList<>();
        Store store = storeRepository.findByStoreId(storeId);
        List<CouponCommercial> couponCommercials = couponCommercialRepository.findByCommercialIdAndStatus(store.getCommercialId());
        //将业态相关的券放入集合
        for (CouponCommercial couponCommercial : couponCommercials) {
            Coupon coupon = couponRepository.findByIdAndStatusShow(couponCommercial.getCouponId());
            if (coupon == null) {
                continue;
            } else {
                if (date.after(DateUtils.stringToDate(coupon.getShowTimeStart(), DateUtils.TIMESTAMP)) && date.before(DateUtils.stringToDate(coupon.getShowTimeEnd(), DateUtils.TIMESTAMP))) {
                    couponList.add(coupon);
                }
            }
        }
        //将商户相关的券放入集合
        List<StoreCoupon> storeCouponList = storeCouponService.queryByStoreId(storeId, page, size);
        for (StoreCoupon storeCoupon : storeCouponList) {
            Coupon coupon = couponRepository.findByIdAndStatusShow(storeCoupon.getCouponId());
            if (coupon == null) {
                continue;
            } else {
                if (date.after(DateUtils.stringToDate(coupon.getShowTimeStart(), DateUtils.TIMESTAMP)) && date.before(DateUtils.stringToDate(coupon.getShowTimeEnd(), DateUtils.TIMESTAMP))) {
                    couponList.add(coupon);
                }
            }
        }
        return couponList;
    }


    /**
     * 查询优惠券列表
     *
     * @param request
     * @return
     */
    public List<CouponDTO> queryList(CouponRequest request) {

        Date date = new Date();
        List<CouponDTO> couponDTOList = new LinkedList<>();
        //分页
        Integer page = request.getPage() == null ? 0 : request.getPage();
        Integer size = request.getSize() == null ? 100 : request.getSize();
        int statusHot = request.getStatusHot() == null ? 2 : request.getStatusHot();
        List<ShopMall> couponList = new LinkedList<>();
        if (statusHot == 1) {
            List<ShopMall> shopMalls = shopMallRepository.queryCouponListHot(statusHot, page * size, size);
            for (ShopMall shopMall : shopMalls) {
                //当券的购买时间在开始时间和结束时间之间时，才放到前端显示
                if (date.after(DateUtils.stringToDate(shopMall.getShowTimeStart(), DateUtils.TIMESTAMP)) && date.before(DateUtils.stringToDate(shopMall.getShowTimeEnd(), DateUtils.TIMESTAMP))) {
                    couponList.add(shopMall);
                }
            }
        } else {
            List<ShopMall> shopMalls = shopMallRepository.queryCouponList(page * size, size);
            for (ShopMall shopMall : shopMalls) {
                if (date.after(DateUtils.stringToDate(shopMall.getShowTimeStart(), DateUtils.TIMESTAMP)) && date.before(DateUtils.stringToDate(shopMall.getShowTimeEnd(), DateUtils.TIMESTAMP))) {
                    couponList.add(shopMall);
                }
            }
        }
        for (ShopMall shopMall : couponList) {
            CouponDTO couponDTO = new CouponDTO();
            Coupon coupon = couponRepository.findByCouponId(shopMall.getCouponId());
            BeanUtils.copyProperties(coupon, couponDTO);
            couponDTO.setRemainTotal(shopMall.getRemainTotal().toString());
            //塞图片
            IdDTO idDTO = new IdDTO();
            idDTO.setForeignKeyId(coupon.getId());
            ImageDTO imageDTO = restTemplate.postForObject("http://quanquan-resource/image/image_query", idDTO, ImageDTO.class);
            for (Image image : imageDTO.getImageDTOs()) {
                if (image.getLogo()) {
                    coupon.setImage(image.getImageAddress());
                    couponRepository.saveAndFlush(coupon);
                    couponDTO.setImage(image.getImageAddress());
                }
            }
            couponDTO.setShopMallId(shopMall.getId());
            couponDTO.setValueType(shopMall.getValueType());
            couponDTO.setPrice(shopMall.getPrice());
            couponDTO.setIntegral(shopMall.getIntegral());
            couponDTOList.add(couponDTO);
        }
        return couponDTOList;
    }


    /**
     * 查询优惠券列表
     *
     * @param request
     * @return
     */
    public List<CouponDTO> queryList1(CouponRequest request) {
        Date date = new Date();
        List<CouponDTO> couponDTOList = new LinkedList<>();
        //分页
        Integer page = request.getPage() == null ? 0 : request.getPage();
        Integer size = request.getSize() == null ? 100 : request.getSize();
        int statusHot = request.getStatusHot() == null ? 2 : request.getStatusHot();
        List<Coupon> couponList = new LinkedList<>();
        if (statusHot == 1) {
            List<Coupon> couponList1 = couponRepository.queryListByStastusHot(statusHot, page * size, size);
            for (Coupon coupon : couponList1) {
                //当券的购买时间在开始时间和结束时间之间时，才放到前端显示
                if (date.after(DateUtils.stringToDate(coupon.getShowTimeStart(), DateUtils.TIMESTAMP)) && date.before(DateUtils.stringToDate(coupon.getShowTimeEnd(), DateUtils.TIMESTAMP))) {
                    couponList.add(coupon);
                }
            }
        } else {
            List<Coupon> couponList1 = couponRepository.queryList(page * size, size);
            for (Coupon coupon : couponList1) {
                if (date.after(DateUtils.stringToDate(coupon.getShowTimeStart(), DateUtils.TIMESTAMP)) && date.before(DateUtils.stringToDate(coupon.getShowTimeEnd(), DateUtils.TIMESTAMP))) {
                    couponList.add(coupon);
                }
            }
        }
        for (Coupon localCoupon : couponList) {
            CouponDTO couponDTO = new CouponDTO();
            BeanUtils.copyProperties(localCoupon, couponDTO);
            if (localCoupon.getSumType() == 1) {
                couponDTO.setRemainTotal("充足");
            } else {
                couponDTO.setRemainTotal(localCoupon.getRemainTotal().toString());
            }
            //塞图片
            IdDTO idDTO = new IdDTO();
            idDTO.setForeignKeyId(localCoupon.getId());
            ImageDTO imageDTO = restTemplate.postForObject("http://quanquan-resource/image/image_query", idDTO, ImageDTO.class);
            for (Image image : imageDTO.getImageDTOs()) {
                if (image.getLogo()) {
                    localCoupon.setImage(image.getImageAddress());
                    couponRepository.saveAndFlush(localCoupon);
                    couponDTO.setImage(image.getImageAddress());
                }
            }
            couponDTOList.add(couponDTO);
        }
        return couponDTOList;
    }


    public PageDTO<CouponDTO> queryByCondition(CouponRequest requestBody) {
        //分页
        Integer page = null == requestBody.getPage() ? 0 : requestBody.getPage();
        Integer size = null == requestBody.getSize() ? 10 : requestBody.getSize();
        //优惠券创建时间区间
        String fromDate = requestBody.getFromDate();
        String toDate = requestBody.getToDate();
        //优惠券审核状态
        //Integer checkState = requestBody.getCheckState();
        Integer status = requestBody.getStatus();
        Integer statusHot = requestBody.getStatusHot();
        // Integer type = requestBody.getType();
        //排序状态

        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        //搜索关键词
        String keyword = requestBody.getKeyword();
        Pageable pageable = PageRequest.of(page, size, sort);
        Page<Coupon> paged = couponRepository.findAll((Specification<Coupon>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            // 创建具体查询条件
            if (null != status) {
                predicates.add(criteriaBuilder.equal(root.get("status").as(Integer.class), status));
            }
            if (null != statusHot) {
                predicates.add(criteriaBuilder.equal(root.get("statusHot").as(Integer.class), statusHot));
            }
            if (StringUtil.isNotEmpty(fromDate)) {
                Date startOfDay = DateUtils.getStartOfDay(DateUtils.strToDate(fromDate, DateUtils.DATE));
                predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime").as(Date.class), startOfDay));
            }
            if (StringUtil.isNotEmpty(toDate)) {
                Date endOfDay = DateUtils.getEndOfDay(DateUtils.strToDate(toDate, DateUtils.DATE));
                predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime").as(Date.class), endOfDay));
            }
            if (StringUtil.isNotEmpty(keyword)) {
                Predicate p1 = criteriaBuilder.like(root.get("name").as(String.class), "%" + keyword + "%");
                Predicate p2 = criteriaBuilder.or(criteriaBuilder.like(root.get("couponDesc").as(String.class), "%" + keyword + "%"), p1);
                predicates.add(p2);
            }

            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        }, pageable);
        List<CouponDTO> couponDTOList = new LinkedList<>();
        for (Coupon coupon : paged.getContent()) {
            CouponDTO couponDTO = new CouponDTO();
            BeanUtils.copyProperties(coupon, couponDTO);
            if (Integer.valueOf(1).equals(coupon.getSumType())) {
                couponDTO.setRemainTotal("充足");
            } else {
                couponDTO.setRemainTotal(coupon.getRemainTotal().toString());
            }
            if (coupon.getSumType() == 0) {
                List<CouponCode> couponCodeList = couponCodeRepository.findByCouponId(coupon.getId());
                couponDTO.setCancelCount(couponCodeList.size());
                if (coupon.getSumTatal() - coupon.getRemainTotal() <= 0) {
                    couponDTO.setCancelRatio("0.00%");
                } else {
                    Integer sendCount = coupon.getSumTatal() - coupon.getRemainTotal();
                    Integer cancelCount = couponCodeList.size();
                    float num = (float) cancelCount / sendCount;
                    DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                    String s = df.format(num * 100);//返回的是String类型
                    couponDTO.setCancelRatio(s + "%");
                }
            } else {
                List<CouponCode> couponCodeList1 = couponCodeRepository.findByCouponIdAndStatus(coupon.getId());
                List<CouponCode> couponCodeList = couponCodeRepository.findByCouponId(coupon.getId());
                couponDTO.setCancelCount(couponCodeList.size());
                if (couponCodeList1.size() <= 0) {
                    couponDTO.setCancelRatio("0.00%");
                } else {
                    Integer sendCount = couponCodeList1.size();
                    Integer cancelCount = couponCodeList.size();
                    float num = (float) cancelCount / sendCount;
                    DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                    String s = df.format(num * 100);//返回的是String类型
                    couponDTO.setCancelRatio(s + "%");
                }
            }
            IdDTO idDTO = new IdDTO();
            idDTO.setForeignKeyId(coupon.getId());
            ImageDTO imageDTO = restTemplate.postForObject("http://quanquan-resource/image/image_query", idDTO, ImageDTO.class);
            for (Image image : imageDTO.getImageDTOs()) {
                if (image.getLogo()) {
                    coupon.setImage(image.getImageAddress());
                    couponRepository.saveAndFlush(coupon);
                    couponDTO.setImage(image.getImageAddress());
                } else {
                    coupon.setPicture(image.getImageAddress());
                    couponRepository.saveAndFlush(coupon);
                    couponDTO.setPicture(image.getImageAddress());
                }
            }
            couponDTOList.add(couponDTO);
        }
        PageDTO<CouponDTO> dto = new PageDTO<>();
        dto.setTotal(paged.getTotalElements());
        dto.setList(couponDTOList);
        dto.setPage(page);
        dto.setPageSize(size);
        dto.setKeyword(requestBody.getKeyword());
        dto.setTotalPage(paged.getTotalPages());
        dto.setFromDate(fromDate);
        dto.setToDate(toDate);
        return dto;
    }

    /**
     * 查看券详情
     *
     * @param id
     * @return
     */
    public CouponDTO queryById(String id, Integer queryStatus, String userId) {
        ShopMall shopMall = shopMallRepository.findByStatusRemoveAndId(id);
        Coupon coupon = couponRepository.findByCouponId(shopMall.getCouponId());
        Date date = new Date();
        //添加历史记录
        if (queryStatus != null) {
            if (queryStatus == 0) {
                CouponHistory couponHistory = couponHistoryRepository.queryByUserIdAndCouponId(userId, id);
                if (couponHistory != null) {
                    couponHistory.setStatusRemove(0);
                    couponHistory.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    couponHistoryRepository.saveAndFlush(couponHistory);
                } else {
                    CouponHistory localHistory = new CouponHistory();
                    localHistory.setId(UUIDGenerator.getUUID());
                    localHistory.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    localHistory.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    localHistory.setStatusShow(0);
                    localHistory.setStatusRemove(0);
                    localHistory.setCouponId(coupon.getId());
                    localHistory.setCountent(coupon.getName());
                    localHistory.setUserId(userId);
                    couponHistoryRepository.saveAndFlush(localHistory);
                }
            }
        }

        CouponDTO couponDTO = new CouponDTO();
        BeanUtils.copyProperties(coupon, couponDTO);
        //传入storeId用于回显
        List<String> storeIdList = new LinkedList<>();
        List<StoreCoupon> storeCoupons = storeCouponRepository.findByCouponId(coupon.getId());
        for (StoreCoupon storeCoupon : storeCoupons) {
            storeIdList.add(storeCoupon.getStoreId());
        }
        couponDTO.setStoreIdList(storeIdList);
        couponDTO.setRemainTotal(shopMall.getRemainTotal().toString());
        //塞图片
        IdDTO idDTO = new IdDTO();
        idDTO.setForeignKeyId(coupon.getId());
        ImageDTO imageDTO = restTemplate.postForObject("http://quanquan-resource/image/image_query", idDTO, ImageDTO.class);
        for (Image image : imageDTO.getImageDTOs()) {
            if (image.getLogo()) {
                coupon.setImage(image.getImageAddress());
                couponRepository.saveAndFlush(coupon);
                couponDTO.setImage(image.getImageAddress());
            } else {
                coupon.setPicture(image.getImageAddress());
                couponRepository.saveAndFlush(coupon);
                couponDTO.setPicture(image.getImageAddress());
            }
        }
        couponDTO.setShopMallId(shopMall.getId());
        couponDTO.setValueType(shopMall.getValueType());
        couponDTO.setPrice(shopMall.getPrice());
        couponDTO.setIntegral(shopMall.getIntegral());
        return couponDTO;
    }

    /**
     * 查看券详情
     *
     * @param id
     * @return
     */
    public CouponDTO queryById1(String id, Integer queryStatus, String userId) {
        Coupon coupon = couponRepository.findByCouponId(id);
        Date date = new Date();
        //添加历史记录
        if (queryStatus != null) {
            if (queryStatus == 0) {
                CouponHistory couponHistory = couponHistoryRepository.queryByUserIdAndCouponId(userId, id);
                if (couponHistory != null) {
                    couponHistory.setStatusRemove(0);
                    couponHistory.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    couponHistoryRepository.saveAndFlush(couponHistory);
                } else {
                    CouponHistory localHistory = new CouponHistory();
                    localHistory.setId(UUIDGenerator.getUUID());
                    localHistory.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    localHistory.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    localHistory.setStatusShow(0);
                    localHistory.setStatusRemove(0);
                    localHistory.setCouponId(coupon.getId());
                    localHistory.setCountent(coupon.getName());
                    localHistory.setUserId(userId);
                    couponHistoryRepository.saveAndFlush(localHistory);
                }
            }
        }

        CouponDTO couponDTO = new CouponDTO();
        BeanUtils.copyProperties(coupon, couponDTO);
        //传入storeId用于回显
        List<String> storeIdList = new LinkedList<>();
        List<StoreCoupon> storeCoupons = storeCouponRepository.findByCouponId(coupon.getId());
        for (StoreCoupon storeCoupon : storeCoupons) {
            storeIdList.add(storeCoupon.getStoreId());
        }
        couponDTO.setStoreIdList(storeIdList);
        if (coupon.getSumType() == 1) {
            couponDTO.setRemainTotal("充足");
        } else {
            couponDTO.setRemainTotal(coupon.getRemainTotal().toString());
        }
        //塞图片
        IdDTO idDTO = new IdDTO();
        idDTO.setForeignKeyId(coupon.getId());
        ImageDTO imageDTO = restTemplate.postForObject("http://quanquan-resource/image/image_query", idDTO, ImageDTO.class);
        for (Image image : imageDTO.getImageDTOs()) {
            if (image.getLogo()) {
                coupon.setImage(image.getImageAddress());
                couponRepository.saveAndFlush(coupon);
                couponDTO.setImage(image.getImageAddress());
            } else {
                coupon.setPicture(image.getImageAddress());
                couponRepository.saveAndFlush(coupon);
                couponDTO.setPicture(image.getImageAddress());
            }
        }
        return couponDTO;
    }

    /**
     * 模糊查询券列表
     *
     * @param request
     * @return
     */
    public List<CouponDTO> queryListByCouponName(CouponRequest request) {
        Date date = new Date();
        List<CouponDTO> couponDTOList = new LinkedList<>();
        Integer page = request.getPage() == null ? 0 : request.getPage();
        Integer size = request.getSize() == null ? 100 : request.getSize();
        List<ShopMall> shopMalls = shopMallRepository.queryCouponListCouponName(request.getName(), page * size, size);
        for (ShopMall shopMall : shopMalls) {
            if (date.before(DateUtils.stringToDate(shopMall.getShowTimeStart(), DateUtils.TIMESTAMP)) || date.after(DateUtils.stringToDate(shopMall.getShowTimeEnd(), DateUtils.TIMESTAMP))) {
                continue;
            }
            CouponDTO couponDTO = new CouponDTO();
            Coupon coupon = couponRepository.findByCouponId(shopMall.getCouponId());
            BeanUtils.copyProperties(coupon, couponDTO);
            couponDTO.setRemainTotal(shopMall.getRemainTotal().toString());
            couponDTO.setShopMallId(shopMall.getId());
            couponDTO.setValueType(shopMall.getValueType());
            couponDTO.setPrice(shopMall.getPrice());
            couponDTO.setIntegral(shopMall.getIntegral());
            //塞图片
            IdDTO idDTO = new IdDTO();
            idDTO.setForeignKeyId(coupon.getId());
            ImageDTO imageDTO = restTemplate.postForObject("http://quanquan-resource/image/image_query", idDTO, ImageDTO.class);
            for (Image image : imageDTO.getImageDTOs()) {
                if (image.getLogo()) {
                    coupon.setImage(image.getImageAddress());
                    couponRepository.saveAndFlush(coupon);
                    couponDTO.setImage(image.getImageAddress());
                }
            }
            couponDTOList.add(couponDTO);
        }
        return couponDTOList;
    }

    /**
     * 模糊查询券列表
     *
     * @param request
     * @return
     */
    public List<CouponDTO> queryListByCouponName1(CouponRequest request) {
        Date date = new Date();
        List<CouponDTO> couponDTOList = new LinkedList<>();
        Integer page = request.getPage() == null ? 0 : request.getPage();
        Integer size = request.getSize() == null ? 100 : request.getSize();
        List<Coupon> couponList = couponRepository.queryListByCouponName(request.getName(), page * size, size);
        for (Coupon coupon : couponList) {
            if (date.before(DateUtils.stringToDate(coupon.getShowTimeStart(), DateUtils.TIMESTAMP)) || date.after(DateUtils.stringToDate(coupon.getShowTimeEnd(), DateUtils.TIMESTAMP))) {
                continue;
            }
            CouponDTO couponDTO = new CouponDTO();
            BeanUtils.copyProperties(coupon, couponDTO);
            if (coupon.getSumType() == 1) {
                couponDTO.setRemainTotal("充足");
            } else {
                couponDTO.setRemainTotal(coupon.getRemainTotal().toString());
            }
            //塞图片
            IdDTO idDTO = new IdDTO();
            idDTO.setForeignKeyId(coupon.getId());
            ImageDTO imageDTO = restTemplate.postForObject("http://quanquan-resource/image/image_query", idDTO, ImageDTO.class);
            for (Image image : imageDTO.getImageDTOs()) {
                if (image.getLogo()) {
                    coupon.setImage(image.getImageAddress());
                    couponRepository.saveAndFlush(coupon);
                    couponDTO.setImage(image.getImageAddress());
                }
            }
            couponDTOList.add(couponDTO);
        }
        return couponDTOList;
    }

    /**
     * 查看历史商品
     *
     * @param request
     * @return
     */
    public List<Object> queryByUserId(CouponRequest request) {
        List<Object> objectList = new LinkedList<>();
        Integer page = request.getPage() == null ? 0 : request.getPage();
        Integer size = request.getSize() == null ? 100 : request.getSize();
        List<CouponHistory> historyList = historyService.queryCouponByUserId(request.getUserId(), page, size);
        for (CouponHistory couponHistory : historyList) {
            Map<String, Object> map = new HashMap<>();
            map.put("couponId", couponHistory.getCouponId());
            map.put("content", couponHistory.getCountent());
            objectList.add(map);
        }
        return objectList;
    }


    /**
     * 根据优惠券类型查询列表
     *
     * @param request
     * @return
     */
    public List<CouponDTO> queryListByType(CouponRequest request) {
        Date date = new Date();
        List<CouponDTO> couponDTOList = new LinkedList<>();
        Integer page = request.getPage() == null ? 0 : request.getPage();
        Integer size = request.getSize() == null ? 100 : request.getSize();
        List<Coupon> couponList = couponRepository.queryListByType(request.getType(), page * size, size);
        for (Coupon coupon : couponList) {
            if (date.before(DateUtils.stringToDate(coupon.getShowTimeStart(), DateUtils.TIMESTAMP)) || date.after(DateUtils.stringToDate(coupon.getShowTimeEnd(), DateUtils.TIMESTAMP))) {
                continue;
            }
            CouponDTO couponDTO = new CouponDTO();
            BeanUtils.copyProperties(coupon, couponDTO);
            //塞图片
            IdDTO idDTO = new IdDTO();
            idDTO.setForeignKeyId(coupon.getId());
            ImageDTO imageDTO = restTemplate.postForObject("http://quanquan-resource/image/image_query", idDTO, ImageDTO.class);
            for (Image image : imageDTO.getImageDTOs()) {
                if (image.getLogo()) {
                    coupon.setImage(image.getImageAddress());
                    couponRepository.saveAndFlush(coupon);
                    couponDTO.setImage(image.getImageAddress());
                }
            }
            couponDTOList.add(couponDTO);
        }
        return couponDTOList;
    }

    /**
     * 根据优惠券支付类型查询列表
     *
     * @param request
     * @return
     */
    public List<CouponDTO> queryListByValueType(CouponRequest request) {
        Date date = new Date();
        List<CouponDTO> couponDTOList = new LinkedList<>();
        Integer page = request.getPage() == null ? 0 : request.getPage();
        Integer size = request.getSize() == null ? 100 : request.getSize();
        List<Coupon> couponList = couponRepository.queryListByValueType(request.getValueType(), page * size, size);
        for (Coupon coupon : couponList) {
            if (date.before(DateUtils.stringToDate(coupon.getShowTimeStart(), DateUtils.TIMESTAMP)) || date.after(DateUtils.stringToDate(coupon.getShowTimeEnd(), DateUtils.TIMESTAMP))) {
                continue;
            }
            CouponDTO couponDTO = new CouponDTO();
            BeanUtils.copyProperties(coupon, couponDTO);
            //塞图片
            IdDTO idDTO = new IdDTO();
            idDTO.setForeignKeyId(coupon.getId());
            ImageDTO imageDTO = restTemplate.postForObject("http://quanquan-resource/image/image_query", idDTO, ImageDTO.class);
            for (Image image : imageDTO.getImageDTOs()) {
                if (image.getLogo()) {
                    coupon.setImage(image.getImageAddress());
                    couponRepository.saveAndFlush(coupon);
                    couponDTO.setImage(image.getImageAddress());
                }
            }
            couponDTOList.add(couponDTO);
        }
        return couponDTOList;
    }

    /**
     * 根据优惠券支付类型和券类型联合查询列表
     *
     * @param request
     * @return
     */
    public List<CouponDTO> queryListByValueTypeAndType1(CouponRequest request) {
        Date date = new Date();
        List<CouponDTO> couponDTOList = new LinkedList<>();
        Integer page = request.getPage() == null ? 0 : request.getPage();
        Integer size = request.getSize() == null ? 100 : request.getSize();
        List<Coupon> couponList = new LinkedList<>();
        // TODO
        if (request.getType() == 0 && request.getValueType() == 0) {
            couponList = couponRepository.queryList(page * size, size);
        } else if (request.getValueType() == 0 && request.getType() != 0) {
            couponList = couponRepository.queryListByType(request.getType(), page * size, size);
        } else if (request.getValueType() != 0 && request.getType() == 0) {
            couponList = couponRepository.queryListByValueType(request.getValueType(), page * size, size);
        } else {
            couponList = couponRepository.queryListByValueTypeAndType(request.getValueType(), page * size, size, request.getType());
        }
        for (Coupon coupon : couponList) {
            if (date.before(DateUtils.stringToDate(coupon.getShowTimeStart(), DateUtils.TIMESTAMP)) || date.after(DateUtils.stringToDate(coupon.getShowTimeEnd(), DateUtils.TIMESTAMP))) {
                continue;
            }
            CouponDTO couponDTO = new CouponDTO();
            BeanUtils.copyProperties(coupon, couponDTO);
            if (coupon.getSumType() == 1) {
                couponDTO.setRemainTotal("充足");
            } else {
                couponDTO.setRemainTotal(coupon.getRemainTotal().toString());
            }
            //塞图片
            IdDTO idDTO = new IdDTO();
            idDTO.setForeignKeyId(coupon.getId());
            ImageDTO imageDTO = restTemplate.postForObject("http://quanquan-resource/image/image_query", idDTO, ImageDTO.class);
            for (Image image : imageDTO.getImageDTOs()) {
                if (image.getLogo()) {
                    coupon.setImage(image.getImageAddress());
                    couponRepository.saveAndFlush(coupon);
                    couponDTO.setImage(image.getImageAddress());
                }
            }
            couponDTOList.add(couponDTO);
        }
        return couponDTOList;
    }

    /**
     * 根据优惠券支付类型和券类型联合查询列表(新)
     *
     * @param request
     * @return
     */
    public List<CouponDTO> queryListByValueTypeAndType(CouponRequest request) {
        Date date = new Date();
        List<CouponDTO> couponDTOList = new LinkedList<>();
        Integer page = request.getPage() == null ? 0 : request.getPage();
        Integer size = request.getSize() == null ? 100 : request.getSize();
        List<ShopMall> shopMalls = new LinkedList<>();
        // TODO
        if (request.getType() == 0 && request.getValueType() == 0) {
            shopMalls = shopMallRepository.queryCouponList(page * size, size);
        } else if (request.getValueType() == 0 && request.getType() != 0) {
            shopMalls = shopMallRepository.queryCouponListByType(request.getType(), page * size, size);
        } else if (request.getValueType() != 0 && request.getType() == 0) {
            shopMalls = shopMallRepository.queryCouponListByValueType(request.getValueType(), page * size, size);
        } else {
            shopMalls = shopMallRepository.queryCouponListByTypeAndValueType(request.getType(), request.getValueType(), page * size, size);
        }
        for (ShopMall shopMall : shopMalls) {
            if (date.before(DateUtils.stringToDate(shopMall.getShowTimeStart(), DateUtils.TIMESTAMP)) || date.after(DateUtils.stringToDate(shopMall.getShowTimeEnd(), DateUtils.TIMESTAMP))) {
                continue;
            }
            Coupon coupon = couponRepository.findByCouponId(shopMall.getCouponId());
            CouponDTO couponDTO = new CouponDTO();
            BeanUtils.copyProperties(coupon, couponDTO);
            couponDTO.setRemainTotal(shopMall.getRemainTotal().toString());
            couponDTO.setShopMallId(shopMall.getId());
            couponDTO.setValueType(shopMall.getValueType());
            couponDTO.setPrice(shopMall.getPrice());
            couponDTO.setIntegral(shopMall.getIntegral());
            //塞图片
            IdDTO idDTO = new IdDTO();
            idDTO.setForeignKeyId(coupon.getId());
            ImageDTO imageDTO = restTemplate.postForObject("http://quanquan-resource/image/image_query", idDTO, ImageDTO.class);
            for (Image image : imageDTO.getImageDTOs()) {
                if (image.getLogo()) {
                    coupon.setImage(image.getImageAddress());
                    couponRepository.saveAndFlush(coupon);
                    couponDTO.setImage(image.getImageAddress());
                }
            }
            couponDTOList.add(couponDTO);
        }
        return couponDTOList;
    }

    /**
     * 查看获得的优惠券列表
     *
     * @param request
     * @return
     */
    public List<Object> queryCodeListByUserId(CouponCodeRequest request) {
        List<Object> objectList = new LinkedList<>();
        Integer page = request.getPage() == null ? 0 : request.getPage();
        Integer size = request.getSize() == null ? 10000 : request.getSize();
        //request.getType() 0 未过期券  1过期券
        if (request.getType() == 0) {
            //request.getStatus()  0未使用 1已使用 2已核销
            Integer type = 1;
            List<CouponCode> couponCodeList = couponCodeRepository.queryCodeListByUserId(request.getUserId(), request.getStatus(), page * size, size, type);
            for (CouponCode couponCode : couponCodeList) {
                Map<String, Object> map = new HashMap<>();
                Coupon coupon = couponRepository.findByCouponIdDetail(couponCode.getCouponId());
                IdDTO idDTO = new IdDTO();
                if (coupon == null) {
                    continue;
                }
                idDTO.setForeignKeyId(coupon.getId());
                ImageDTO imageDTO = restTemplate.postForObject("http://quanquan-resource/image/image_query", idDTO, ImageDTO.class);
                map.put("couponId", coupon.getId());
                map.put("image", imageDTO.getImageDTOs().get(0).getImageAddress());
                map.put("couponName", coupon.getName());
                map.put("couponCodeId", couponCode.getId());
                map.put("couponCode", couponCode.getCouponCode());
                map.put("endTime", couponCode.getUseTimeEnd());
                objectList.add(map);
            }
        } else {
            List<CouponCode> couponCodeList = couponCodeRepository.queryOverdue(request.getUserId(), page * size, size);
            for (CouponCode couponCode : couponCodeList) {
                Map<String, Object> map = new HashMap<>();
                Coupon coupon = couponRepository.findByCouponId(couponCode.getCouponId());
                IdDTO idDTO = new IdDTO();
                idDTO.setForeignKeyId(coupon.getId());
                ImageDTO imageDTO = restTemplate.postForObject("http://quanquan-resource/image/image_query", idDTO, ImageDTO.class);
                map.put("couponId", coupon.getId());
                map.put("image", imageDTO.getImageDTOs().get(0).getImageAddress());
                map.put("couponName", coupon.getName());
                map.put("couponCodeId", couponCode.getId());
                map.put("couponCode", couponCode.getCouponCode());
                map.put("endTime", couponCode.getUseTimeEnd());
                objectList.add(map);
            }
        }
        return objectList;
    }

    /**
     * 查看获得的停车券列表
     *
     * @param request
     * @return
     */
    public List<Object> queryParkingCouponByUserId(CouponCodeRequest request) {
        List<Object> objectList = new LinkedList<>();
        Integer page = request.getPage() == null ? 0 : request.getPage();
        Integer size = request.getSize() == null ? 10000 : request.getSize();
        //request.getType() 0 未过期券  1过期券
        if (request.getType() == 0) {
            //request.getStatus()  0未使用 1已使用
            Integer type = 3;
            List<CouponCode> couponCodeList = couponCodeRepository.queryCodeListByUserId(request.getUserId(), request.getStatus(), page * size, size, type);
            for (CouponCode couponCode : couponCodeList) {
                Map<String, Object> map = new HashMap<>();
                Coupon coupon = couponRepository.findByCouponIdDetail(couponCode.getCouponId());
                IdDTO idDTO = new IdDTO();
                idDTO.setForeignKeyId(coupon.getId());
                ImageDTO imageDTO = restTemplate.postForObject("http://quanquan-resource/image/image_query", idDTO, ImageDTO.class);
                for (Image image : imageDTO.getImageDTOs()) {
                    if (image.getLogo()) {
                        map.put("image", image.getImageAddress());
                    }
                }
                map.put("couponId", coupon.getId());
                map.put("couponName", coupon.getName());
                map.put("couponCodeId", couponCode.getId());
                map.put("couponCode", couponCode.getCouponCode());
                map.put("endTime", couponCode.getUseTimeEnd());
                map.put("disType", coupon.getDisType());
                map.put("value", coupon.getDisValue());
                objectList.add(map);

            }
        } else {
            List<CouponCode> couponCodeList = couponCodeRepository.queryOverdue(request.getUserId(), page * size, size);
            for (CouponCode couponCode : couponCodeList) {
                Map<String, Object> map = new HashMap<>();
                Coupon coupon = couponRepository.findByCouponId(couponCode.getCouponId());
                IdDTO idDTO = new IdDTO();
                idDTO.setForeignKeyId(coupon.getId());
                ImageDTO imageDTO = restTemplate.postForObject("http://quanquan-resource/image/image_query", idDTO, ImageDTO.class);
                map.put("couponId", coupon.getId());
                for (Image image : imageDTO.getImageDTOs()) {
                    if (image.getLogo()) {
                        map.put("image", image.getImageAddress());
                    }
                }
                map.put("couponName", coupon.getName());
                map.put("couponCodeId", couponCode.getId());
                map.put("couponCode", couponCode.getCouponCode());
                map.put("endTime", couponCode.getUseTimeEnd());
                map.put("disType", coupon.getDisType());
                map.put("value", coupon.getDisValue());
                objectList.add(map);

            }
        }
        return objectList;
    }


    /**
     * 查看自己的优惠券详情(新)
     *
     * @param request
     * @return
     */
    public Map<String, Object> queryCodeByIdAndUserId(CouponCodeRequest request) {
        Map<String, Object> map = new HashMap<>();
        CouponCode couponCode = couponCodeRepository.queryById(request.getId());
        ShopMall shopMall = shopMallRepository.findByStatusRemoveAndId(couponCode.getShopMallId());
        Coupon coupon = couponRepository.findByCouponId(couponCode.getCouponId());
        map.put("couponId", coupon.getId());
        map.put("couponName", coupon.getName());
        map.put("couponCodeId", couponCode.getId());
        if (shopMall == null) {
            map.put("valueType", shopMall.getValueType());
            map.put("integral", shopMall.getIntegral());
            map.put("price", shopMall.getPrice());
        } else {
            map.put("valueType", 0);
            map.put("integral", 0);
            map.put("price", 0);
        }
        map.put("couponCode", couponCode.getCouponCode());
        map.put("endTime", couponCode.getUseTimeEnd());
        map.put("couponDESC", coupon.getUseRule());
        return map;
    }

    /**
     * 查看自己的优惠券详情
     *
     * @param request
     * @return
     */
    public Map<String, Object> queryCodeByIdAndUserId1(CouponCodeRequest request) {
        Map<String, Object> map = new HashMap<>();
        CouponCode couponCode = couponCodeRepository.queryById(request.getId());
        Coupon coupon = couponRepository.findByCouponId(couponCode.getCouponId());
        map.put("couponId", coupon.getId());
        map.put("couponName", coupon.getName());
        map.put("couponCodeId", couponCode.getId());
        map.put("integral", coupon.getIntegral());
        map.put("price", coupon.getPrice());
        map.put("couponCode", couponCode.getCouponCode());
        map.put("endTime", couponCode.getUseTimeEnd());
        map.put("couponDESC", coupon.getUseRule());
        return map;
    }

    /**
     * 通过券码查看优惠券详情
     *
     * @param request
     * @return
     */
    public Map<String, Object> queryCodeByCouponCode(CouponCodeRequest request) {
        Map<String, Object> map = new HashMap<>();
        CouponCode couponCode = couponCodeRepository.queryByCouponCode(request.getCouponCode());
        Coupon coupon = couponRepository.findByCouponId(couponCode.getCouponId());
        map.put("couponId", coupon.getId());
        map.put("couponName", coupon.getName());
        map.put("couponCodeId", couponCode.getId());
        map.put("integral", coupon.getIntegral());
        map.put("price", coupon.getPrice());
        map.put("couponCode", couponCode.getCouponCode());
        map.put("endTime", couponCode.getUseTimeEnd());
        map.put("couponDESC", coupon.getUseRule());
        return map;
    }


    /**
     * 核销用户登录
     *
     * @param request
     * @return
     */
    public Admin login(AdminRequest request) {
        String password = DecriptUtils.MD5(request.getPassword());
        Admin admin = adminRepository.findByAccountAndPassword(request.getAccount(), password);
        if (admin == null) {
            return null;
        }
        return admin;
    }

    /**
     * 核销人验证密码
     *
     * @param request
     * @return
     */
    public boolean checkPassword(AdminRequest request) {
        Admin admin = adminRepository.findByAccount(request.getAccount());
        if (admin != null) {
            String password = DecriptUtils.MD5(request.getPassword());
            if (admin.getPassword().equals(password)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 核销人修改密码
     *
     * @param request
     * @return
     */
    public boolean editPassword(AdminRequest request) {
        Admin admin = adminRepository.findByAccount(request.getAccount());
        if (admin != null) {
            String password = DecriptUtils.MD5(request.getPassword());
            admin.setPassword(password);
            admin.setUpdateTime(DateUtils.dateToString(new Date(), DateUtils.TIMESTAMP));
            adminRepository.saveAndFlush(admin);
            return true;
        }
        return false;
    }

    public List<Admin> findAdminsByIds(List<String> adminIds) {
        List<Admin> admins = new ArrayList<>();
        for (String adminId : adminIds) {
            Admin admin = adminRepository.findByAdminId(adminId);
            admins.add(admin);
        }
        return admins;
    }

    /**
     * 优惠券使用并核销
     *
     * @param request
     * @return
     */
    public String cancelCouponCode(CouponCodeRequest request) {
        Date date = new Date();
        CouponCode couponCode = couponCodeRepository.queryByCouponCodeAndUserId1(request.getCouponCode());
        Admin admin = adminRepository.findByAdminId(request.getUseAdminId());
        if (admin.getLevel() == 1) {
            System.out.println("核销最高权限");
        } else {
            Coupon coupon = couponRepository.findByCouponId(couponCode.getCouponId());
            if (coupon.getBindType() != null) {
                if (coupon.getBindType() == 1) {
                    //根据商户判断核销员是否可以核销此券
                    StoreCoupon storeCoupon = storeCouponRepository.findByCouponIdAndStoreId(coupon.getId(), admin.getStoreId());
                    if (storeCoupon == null) {
                        return "无权限核销此券";
                    }
                } else {
                    //根据业态判断核销员是否可以核销此券
                    List<StoreCommercial> storeCommercials = storeCommercialRepository.findByStoreIdAndStatus(admin.getStoreId());
                    String commercialId = storeCommercials.get(0).getCommercialId();
                    CouponCommercial couponCommercial = couponCommercialRepository.findByCouponIdAndCommercialId(coupon.getId(), commercialId);
                    if (couponCommercial == null) {
                        return "无权限核销此券";
                    }
                }
            } else {
                return "无权限核销此券";
            }
        }
        if (couponCode != null) {
            if (couponCode.getStatus() == 1) {
                return "券已核销";
            }
            if (date.before(DateUtils.stringToDate(couponCode.getUseTimeStart(), DateUtils.TIMESTAMP))) {
                return "未到使用时间";
            }
            if (date.after(DateUtils.stringToDate(couponCode.getUseTimeEnd(), DateUtils.TIMESTAMP))) {
                return "该券已过期";
            }
            Coupon coupon = couponRepository.findByCouponIdAndStatus(couponCode.getCouponId());
            if (coupon.getType() == 3) {
                return "券类型错误";
            }
            if (couponCode.getStatus() == 0) {
                couponCode.setStatus(1);
                couponCode.setUseAdminId(admin.getId());
                couponCode.setAdminName(admin.getName());
                couponCode.setUseTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                couponCodeRepository.saveAndFlush(couponCode);
                return "核销成功";
            }
            return "核销失败";
        }
        return "用户没有对应商品";
    }

    /**
     * 通过券码查询券详情
     *
     * @param couponCode
     * @return
     */
    public Map<String, Object> queryByCouponCode1(String couponCode) {
        Map<String, Object> map = new HashMap<>();
        CouponCode couponCode1 = couponCodeRepository.queryByCouponCodeAndUserId1(couponCode);
        if (couponCode1 == null) {
            return null;
        }
        Coupon coupon = couponRepository.findByCouponId(couponCode1.getCouponId());
        map.put("type", couponCode1.getStatus());
        map.put("useEndTime", couponCode1.getUseTimeEnd());
        map.put("couponId", coupon.getId());
        map.put("couponName", coupon.getName());
        map.put("couponCodeId", couponCode1.getId());
        map.put("couponCode", couponCode1.getCouponCode());
        map.put("integral", coupon.getIntegral());
        map.put("price", coupon.getPrice());
        map.put("cancelTime", couponCode1.getUseTime());
        map.put("couponDESC", coupon.getUseRule());
        if (coupon.getType() == 1) {
            map.put("couponType", "优惠券");
        } else if (coupon.getType() == 2) {
            map.put("couponType", "商品券");
        } else {
            map.put("couponType", "停车券");
        }
        return map;
    }

    /**
     * 通过券码查询券详情(新)
     *
     * @param couponCode
     * @return
     */
    public Map<String, Object> queryByCouponCode(String couponCode) {
        Map<String, Object> map = new HashMap<>();
        CouponCode couponCode1 = couponCodeRepository.queryByCouponCodeAndUserId1(couponCode);
        if (couponCode1 == null) {
            return null;
        }
        shopMallRepository.findByStatusRemoveAndId(couponCode1.getShopMallId());
        Coupon coupon = couponRepository.findByCouponId(couponCode1.getCouponId());
        map.put("type", couponCode1.getStatus());
        map.put("useEndTime", couponCode1.getUseTimeEnd());
        map.put("couponId", coupon.getId());
        map.put("couponName", coupon.getName());
        map.put("couponCodeId", couponCode1.getId());
        map.put("couponCode", couponCode1.getCouponCode());
        map.put("integral", coupon.getIntegral());
        map.put("price", coupon.getPrice());
        map.put("cancelTime", couponCode1.getUseTime());
        map.put("couponDESC", coupon.getUseRule());
        if (coupon.getType() == 1) {
            map.put("couponType", "优惠券");
        } else if (coupon.getType() == 2) {
            map.put("couponType", "商品券");
        } else {
            map.put("couponType", "停车券");
        }
        return map;
    }


    public PageDTO<CouponCodeDTO> cancelRecordByCondition(CouponCodeRequest requestBody) {
        //分页
        Integer page = null == requestBody.getPage() ? 0 : requestBody.getPage();
        Integer size = null == requestBody.getSize() ? 10 : requestBody.getSize();
        //优惠券创建时间区间
        String fromDate = requestBody.getFromDate();
        String toDate = requestBody.getToDate();
        Integer type = requestBody.getType();
        //排序状态

        Sort sort = new Sort(Sort.Direction.DESC, "useTime");
        //搜索关键词
        String keyword = requestBody.getKeyword();
        Pageable pageable = PageRequest.of(page, size, sort);
        Page<CouponCode> paged = couponCodeRepository.findAll((Specification<CouponCode>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();


            if (StringUtil.isNotEmpty(keyword)) {
                IdDTO idDTO1 = new IdDTO();
                idDTO1.setKeyWord(keyword);
                UserInfoDTO userInfoDTO = restTemplate.postForObject("http://QUANQUAN-USER/user/query_keyword", idDTO1, UserInfoDTO.class);
                if (userInfoDTO != null) {
                    List<DTO.user.UserDTO> users = userInfoDTO.getUserDTOS();
                    if (users.size() > 0) {
                        DTO.user.UserDTO userDTO = users.get(0);
                        predicates.add(criteriaBuilder.equal(root.get("userId").as(String.class), userDTO.getId()));
                    }
                } else {
                    Predicate p1 = criteriaBuilder.like(root.get("couponCode").as(String.class), "%" + keyword + "%");
                    Predicate p2 = criteriaBuilder.or(criteriaBuilder.like(root.get("couponName").as(String.class), "%" + keyword + "%"), p1);
                    Predicate p3 = criteriaBuilder.or(criteriaBuilder.like(root.get("adminName").as(String.class), "%" + keyword + "%"), p2);
                    predicates.add(p3);

                }


            }


            if (StringUtil.isNotEmpty(fromDate)) {
                Date startOfDay = DateUtils.getStartOfDay(DateUtils.strToDate(fromDate, DateUtils.DATE));
                predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("useTime").as(Date.class), startOfDay));
            }
            if (StringUtil.isNotEmpty(toDate)) {
                Date endOfDay = DateUtils.getEndOfDay(DateUtils.strToDate(toDate, DateUtils.DATE));
                predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("useTime").as(Date.class), endOfDay));
            }
//
            predicates.add(criteriaBuilder.equal(root.get("status"), 1));
            predicates.add(criteriaBuilder.equal(root.get("type"), 1));

            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        }, pageable);
        List<CouponCode> couponCodes = paged.getContent();
        List<String> adminIds = couponCodes.stream().filter(distinctByKey(CouponCode::getUseAdminId)).map(CouponCode::getUseAdminId).collect(Collectors.toList());
        List<String> userIds = couponCodes.stream().filter(distinctByKey(CouponCode::getUserId)).map(CouponCode::getUserId).collect(Collectors.toList());
        List<Admin> adminsByIds = findAdminsByIds(adminIds);


        IdDTO idDTO = new IdDTO();
        idDTO.setForeignKeyIds(userIds);

        UserInfoDTO userInfoDTO = restTemplate.postForObject("http://QUANQUAN-USER/user/query_by_id_list", idDTO, UserInfoDTO.class);
        assert userInfoDTO != null;
        List<DTO.user.UserDTO> userDTOS = userInfoDTO.getUserDTOS();
        List<CouponCodeDTO> couponCodeDTOS = new ArrayList<>();
        for (CouponCode couponCode : couponCodes) {
            //通过映射关系来赋值 //TODO 断点看一下
            CouponCodeDTO couponCodeDTO = new CouponCodeDTO();
            BeanUtils.copyProperties(couponCode, couponCodeDTO);
            for (Admin admin : adminsByIds) {
                if (admin.getId().equals(couponCode.getUseAdminId())) {

                    couponCodeDTO.setUseAdminName(admin.getName());
                    couponCodeDTOS.add(couponCodeDTO);

                }


            }
        }
        for (CouponCodeDTO couponCodeDTO : couponCodeDTOS) {
            for (DTO.user.UserDTO userDTO : userDTOS) {
                if (couponCodeDTO.getUserId().equals(userDTO.getId())) {
                    couponCodeDTO.setUseName(userDTO.getMemberName());
                    couponCodeDTO.setPhone(userDTO.getPhone());
                    couponCodeDTO.setMemberCardNum(userDTO.getMemberCardNum());
                }
            }

        }

        PageDTO<CouponCodeDTO> dto = new PageDTO<>();
        dto.setTotal(paged.getTotalElements());
        dto.setList(couponCodeDTOS);
        dto.setPage(page);
        dto.setPageSize(size);
        dto.setKeyword(requestBody.getKeyword());
        dto.setTotalPage(paged.getTotalPages());
        dto.setFromDate(fromDate);
        dto.setToDate(toDate);
        return dto;
    }


    private static <T> java.util.function.Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Set<Object> seen = ConcurrentHashMap.newKeySet();
        return t -> seen.add(keyExtractor.apply(t));
    }

    /**
     * 核销记录
     *
     * @param request
     * @return
     */
    public List<Object> cancelRecord(CouponCodeRequest request) {
        Integer page = request.getPage() == null ? 0 : request.getPage();
        Integer size = request.getSize() == null ? 100 : request.getSize();

        List<Object> objectList = new LinkedList<>();
        List<CouponCode> couponCodeList = new LinkedList<>();
        Integer type = 1;
        Admin localAdmin = adminRepository.findByAdminId(request.getUseAdminId());
        if (localAdmin.getLevel() == 1) {
            couponCodeList = couponCodeRepository.queryByUseAdminId(localAdmin.getId(), page * size, size, type);
        } else {
            if (localAdmin.getLevel() == 2) {
                List<Admin> admins = adminRepository.findByStoreIdAndLevel(localAdmin.getStoreId());
                for (Admin admin1 : admins) {
                    List<CouponCode> couponCodeList1 = couponCodeRepository.queryByUseAdminId(admin1.getId(), page * size, size, type);
                    assert couponCodeList != null;
                    couponCodeList.addAll(couponCodeList1);
                }
            } else {
                couponCodeList = couponCodeRepository.queryByUseAdminId(localAdmin.getId(), page * size, size, type);
            }
        }
        for (CouponCode couponCode : couponCodeList) {
            Admin admin = adminRepository.findByAdminId(couponCode.getUseAdminId());
            if (admin == null) {
                continue;
            }
            Map<String, Object> map = new HashMap<>();
            Coupon coupon = couponRepository.findByCouponId(couponCode.getCouponId());
            map.put("couponId", coupon.getId());
            map.put("couponName", coupon.getName());
            map.put("couponCodeId", couponCode.getId());
            map.put("couponCode", couponCode.getCouponCode());
            map.put("integral", coupon.getIntegral());
            map.put("price", coupon.getPrice());
            map.put("adminName", admin.getName());
            map.put("cancelTime", couponCode.getUseTime());
            map.put("couponDESC", coupon.getUseRule());
            if (coupon.getType() == 1) {
                map.put("couponType", "优惠券");
            } else if (coupon.getType() == 2) {
                map.put("couponType", "商品券");
            } else {
                map.put("couponType", "停车券");
            }
            objectList.add(map);
        }
        return objectList;
    }

    /**
     * 账单减免计费接口(点击优惠券，账单减免计费接口)
     *
     * @param request
     * @return
     */
    public Map<String,Object> useParkingCoupon(CouponCodeRequest request) {
        Map<String,Object> map = new HashMap<>();
        Date date = new Date();
        System.out.println(date);
        CouponCode couponCode = couponCodeRepository.queryByCouponCodeAndUserId1(request.getCouponCode());
        if (couponCode != null) {
            Coupon coupon = couponRepository.findByCouponIdAndStatus(couponCode.getCouponId());
            if (coupon.getType() != 3) {
                map.put("msg","此券非停车券");
                return map;
            }
            if (couponCode.getStatus() == 1) {
                map.put("msg","此券已使用");
                return map;
            }
            if (date.before(DateUtils.stringToDate(couponCode.getUseTimeStart(), DateUtils.TIMESTAMP))) {
                map.put("msg","未到使用时间");
                return map;
            }
            if (date.after(DateUtils.stringToDate(couponCode.getUseTimeEnd(), DateUtils.TIMESTAMP))) {
                map.put("msg","此券已过期");
                return map;
            }

            //根据停车发放券状态判断是否核销
            PayParkingFeeRequest payParkingFeeRequest = new PayParkingFeeRequest();
            // 配置金额抵扣
            payParkingFeeRequest.setDisType(2);
            payParkingFeeRequest.setCouponCode(couponCode.getCouponCode());
            payParkingFeeRequest.setCouponName(coupon.getName());
            payParkingFeeRequest.setPlateNum(request.getCarNumber());
            payParkingFeeRequest.setUserId(request.getUserId());
            payParkingFeeRequest.setType(0);
            if (coupon.getDisType() == 2) {
                payParkingFeeRequest.setFreeMoney(coupon.getDisValue() * 100);
                payParkingFeeRequest.setFreeTime(0);
                payParkingFeeRequest.setOrderNo(request.getOrderNo());
                //封装抵扣细节
                FreeDetail freeDetail = new FreeDetail();
                freeDetail.setCode(couponCode.getCouponCode());
                freeDetail.setMoney(coupon.getDisValue() * 100);
                freeDetail.setTime(0);
                freeDetail.setType(1);
                List<FreeDetail> freeDetails = new LinkedList<>();
                freeDetails.add(freeDetail);
                payParkingFeeRequest.setFreeDetail(freeDetails);
            } else {
                payParkingFeeRequest.setFreeMoney(0);
                payParkingFeeRequest.setFreeTime(coupon.getDisValue() * 60);
                payParkingFeeRequest.setOrderNo(request.getOrderNo());
                //封装抵扣细节
                FreeDetail freeDetail = new FreeDetail();
                freeDetail.setCode(couponCode.getCouponCode());
                freeDetail.setMoney(0);
                freeDetail.setTime(coupon.getDisValue() * 60);
                freeDetail.setType(1);
                List<FreeDetail> freeDetails = new LinkedList<>();
                freeDetails.add(freeDetail);
                payParkingFeeRequest.setFreeDetail(freeDetails);
            }
            String json = Request.postJson(parkingUrl + "ketop_parking/get_payment_recharge", payParkingFeeRequest);
            JSONObject jsonObject = JSONObject.parseObject(json);
            Integer resCode = jsonObject.getInteger("resCode");
            if (0 == resCode) {
                PaymentRechargeDTO paymentRechargeDTO = jsonObject.getJSONObject("data").toJavaObject(PaymentRechargeDTO.class);
                System.out.println(paymentRechargeDTO);
                map.put("msg","SUCCESS");
                map.put("orderNo",paymentRechargeDTO.getOrderNo());
                DecimalFormat df = new DecimalFormat("0.00");
                double fee = paymentRechargeDTO.getPayable().doubleValue();
                String feeYuan = df.format(fee / 100);
                map.put("payable",feeYuan);
                return map;
            }
        }
        map.put("msg","该券不存在，请核实后使用");
        return map;
    }

    /**
     * 账单减免计费接口(点击优惠券，账单减免计费接口)
     *
     * @param request
     * @return
     */
    public String cancelParkingCoupon(CouponCodeRequest request) {
        Date date = new Date();
        System.out.println(date);
        CouponCode couponCode = couponCodeRepository.queryByCouponCodeAndUserId1(request.getCouponCode());
        if (couponCode != null) {
            Coupon coupon = couponRepository.findByCouponIdAndStatus(couponCode.getCouponId());
            if (coupon.getType() != 3) {
                return "此券非停车券";
            }
            if (couponCode.getStatus() == 1) {
                return "此券已使用";
            }
            if (date.before(DateUtils.stringToDate(couponCode.getUseTimeStart(), DateUtils.TIMESTAMP))) {
                return "未到使用时间";
            }
            if (date.after(DateUtils.stringToDate(couponCode.getUseTimeEnd(), DateUtils.TIMESTAMP))) {
                return "此券已过期";
            }
            //根据停车发放券状态判断是否核销
            PayParkingFeeRequest payParkingFeeRequest = new PayParkingFeeRequest();
            // 配置金额抵扣
            payParkingFeeRequest.setDisType(2);
            payParkingFeeRequest.setCouponCode(couponCode.getCouponCode());
            payParkingFeeRequest.setCouponName(coupon.getName());
            payParkingFeeRequest.setPlateNum(request.getCarNumber());
            payParkingFeeRequest.setUserId(request.getUserId());
            payParkingFeeRequest.setType(1);
            if (coupon.getDisType() == 2) {
                payParkingFeeRequest.setFreeMoney(coupon.getDisValue() * 100);
                payParkingFeeRequest.setFreeTime(0);
                payParkingFeeRequest.setOrderNo(request.getOrderNo());
                //封装抵扣细节
                FreeDetail freeDetail = new FreeDetail();
                freeDetail.setCode(couponCode.getCouponCode());
                freeDetail.setMoney(coupon.getDisValue() * 100);
                freeDetail.setTime(0);
                freeDetail.setType(1);
                List<FreeDetail> freeDetails = new LinkedList<>();
                freeDetails.add(freeDetail);
                payParkingFeeRequest.setFreeDetail(freeDetails);
            } else {
                payParkingFeeRequest.setFreeMoney(0);
                payParkingFeeRequest.setFreeTime(coupon.getDisValue() * 60);
                payParkingFeeRequest.setOrderNo(request.getOrderNo());
                //封装抵扣细节
                FreeDetail freeDetail = new FreeDetail();
                freeDetail.setCode(couponCode.getCouponCode());
                freeDetail.setMoney(0);
                freeDetail.setTime(coupon.getDisValue() * 60);
                freeDetail.setType(1);
                List<FreeDetail> freeDetails = new LinkedList<>();
                freeDetails.add(freeDetail);
                payParkingFeeRequest.setFreeDetail(freeDetails);
            }
            String json = Request.postJson(parkingUrl + "ketop_parking/pay_parking_fee", payParkingFeeRequest);
            JSONObject jsonObject = JSONObject.parseObject(json);
            Integer resCode = jsonObject.getInteger("resCode");
            if (0 == resCode) {
                if (couponCode.getStatus() == 0) {
                    couponCode.setStatus(1);
                    couponCode.setUseAdminId("");
                    couponCode.setUseTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    couponCode.setCarNumber(request.getCarNumber());
                    couponCodeRepository.saveAndFlush(couponCode);
                    return "核销成功";
                }
            } else {
                return "抵扣失败";
            }
        }
        return "该券不存在，请核实后使用";
    }


    /**
     * 手动发券
     *
     * @param request
     * @return
     */
    public String sendCoupon(CouponRequest request) {
        Date date = new Date();
        //在保证之前的代码可用的情况下，如果传入单个userId放入集合中
        List<String> userIdList = new LinkedList<>();
        if (request.getUserIdList() == null) {
            userIdList.add(request.getUserId());
        } else {
            userIdList = request.getUserIdList();
        }
        Coupon coupon = couponRepository.findByCouponId(request.getId());
        if (coupon == null) {
            return "没有对应商品";
        }
        String senderName;
        Integer sendRequestType = request.getSendRequestType() == null ? 1 : request.getSendRequestType();
        if (sendRequestType == 1) {
            senderName = "系统";
        } else {
            senderName = request.getSenderName();
        }
        //如果前端不传值，默认发一张
        Integer count = request.getCount() == null ? 1 : request.getCount();
        Date now = new Date();
        //根据优惠券使用期限和券id查找对应的code，并将code锁定
        String useEnd = null;
        if (coupon.getUseTimeType() == 1) {
            useEnd = coupon.getUseTimeEnd();
        }
        if (coupon.getUseTimeType() == 2) {
            useEnd = DateUtils.dateToString(DateUtils.getDateAfterHour(coupon.getUseTimeHour()), DateUtils.TIMESTAMP);
        }
        if (coupon.getUseTimeType() == 3) {
            useEnd = DateUtils.dateToString(DateUtils.getEndOfDay(now), DateUtils.TIMESTAMP);
        }
        if (coupon.getSumType() == 1) {
            for (String userId : userIdList) {
                for (int i = 0; i < count; i++) {
                    CouponCode couponCode = new CouponCode();
                    couponCode.setId(UUIDGenerator.getUUID());
                    couponCode.setCouponCode(DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.getRandomStr());
                    couponCode.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    couponCode.setAddTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    couponCode.setCouponId(coupon.getId());
                    couponCode.setUserId(userId);
                    couponCode.setStatus(0);
                    couponCode.setType(coupon.getType());
                    couponCode.setUseTimeEnd(useEnd);
                    couponCode.setCouponName(coupon.getName());
                    if (coupon.getUseTimeType() == 1) {
                        couponCode.setUseTimeStart(coupon.getUseTimeStart());
                    } else {
                        couponCode.setUseTimeStart(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    }
                    couponCode.setSenderName(senderName);
                    couponCodeRepository.saveAndFlush(couponCode);
                    //推送发券成功模板 TODO
                    //保存发券成功记录
                    SendCouponRecord sendCouponRecord = new SendCouponRecord();
                    sendCouponRecord.setId(UUIDGenerator.getUUID());
                    sendCouponRecord.setCouponId(coupon.getId());
                    sendCouponRecord.setUserId(userId);
                    sendCouponRecord.setSendTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    sendCouponRecord.setStatus(0);
                    sendCouponRecord.setCount(count);
                    sendCouponRecord.setCouponName(coupon.getName());
                    sendCouponRecord.setSenderName(senderName);
                    sendCouponRecordRepository.saveAndFlush(sendCouponRecord);
                }
            }
        } else {
            if (coupon.getRemainTotal() >= userIdList.size() * count) {
                couponRepository.updateRemainTotal(request.getId(), userIdList.size() * count);
                //根据优惠券使用期限和券id查找对应的code，并将code锁定
                for (String userId : userIdList) {
                  /*  for (int i = 0; i < count; i++) {
                        List<CouponCode> couponCodeList = couponCodeRepository.queryByCouponIdAndStatus(coupon.getId());
                        CouponCode couponCode = couponCodeList.get(0);
                        System.out.println(userId);
                        System.out.println(couponCode.getId());
                        if (coupon.getUseTimeType() == 1) {
                            couponCodeRepository.addUserCouponCode1(couponCode.getId(), userId, DateUtils.dateToString(date, DateUtils.TIMESTAMP), senderName, useEnd,coupon.getUseTimeStart());
                        } else {
                            couponCodeRepository.addUserCouponCode1(couponCode.getId(), userId, DateUtils.dateToString(date, DateUtils.TIMESTAMP), senderName, useEnd,DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                        }
                    }*/
                    for (int i = 0; i < count; i++) {
                        List<CouponCode> couponCodeList = couponCodeRepository.queryByCouponIdAndStatus(coupon.getId());
                        addMemberCouponCode(couponCodeList, useEnd, userId, senderName, coupon, 0);
                    }
                    //推送发券成功模板 TODO
                    //保存发券成功记录
                    SendCouponRecord sendCouponRecord = new SendCouponRecord();
                    sendCouponRecord.setId(UUIDGenerator.getUUID());
                    sendCouponRecord.setCouponId(coupon.getId());
                    sendCouponRecord.setUserId(userId);
                    sendCouponRecord.setSendTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    sendCouponRecord.setStatus(0);
                    sendCouponRecord.setCount(count);
                    sendCouponRecord.setCouponName(coupon.getName());
                    sendCouponRecord.setSenderName(senderName);
                    sendCouponRecordRepository.saveAndFlush(sendCouponRecord);
                }
            } else {
                for (String userId : userIdList) {
                    //保存发券失败记录
                    SendCouponRecord sendCouponRecord = new SendCouponRecord();
                    sendCouponRecord.setId(UUIDGenerator.getUUID());
                    sendCouponRecord.setCouponId(coupon.getId());
                    sendCouponRecord.setUserId(userId);
                    sendCouponRecord.setSendTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    sendCouponRecord.setStatus(1);
                    sendCouponRecord.setCount(count);
                    sendCouponRecord.setCouponName(coupon.getName());
                    sendCouponRecord.setSenderName(senderName);
                    sendCouponRecordRepository.saveAndFlush(sendCouponRecord);
                }
                return "商品数量不足";
            }
        }
        return "发券成功";
    }


    /**
     * 发秒杀券
     *
     * @param request
     * @return
     */
    public String sendShoppingKillCoupon(CouponRequest request) {
        Date date = new Date();
        //在保证之前的代码可用的情况下，如果传入单个userId放入集合中
        List<String> userIdList = new LinkedList<>();
        if (request.getUserIdList() == null) {
            userIdList.add(request.getUserId());
        } else {
            userIdList = request.getUserIdList();
        }
        Coupon coupon = couponRepository.findByCouponId(request.getId());
        if (coupon == null) {
            return "没有对应商品";
        }
        String senderName;
        Integer sendRequestType = request.getSendRequestType() == null ? 1 : request.getSendRequestType();
        if (sendRequestType == 1) {
            senderName = "系统";
        } else {
            senderName = request.getSenderName();
        }
        //如果前端不传值，默认发一张
        Integer count = request.getCount() == null ? 1 : request.getCount();
        Date now = new Date();
        //根据优惠券使用期限和券id查找对应的code，并将code锁定
        String useEnd = null;
        if (coupon.getUseTimeType() == 1) {
            useEnd = coupon.getUseTimeEnd();
        }
        if (coupon.getUseTimeType() == 2) {
            useEnd = DateUtils.dateToString(DateUtils.getDateAfterHour(coupon.getUseTimeHour()), DateUtils.TIMESTAMP);
        }
        if (coupon.getUseTimeType() == 3) {
            useEnd = DateUtils.dateToString(DateUtils.getEndOfDay(now), DateUtils.TIMESTAMP);
        }
        if (coupon.getSumType() == 1) {
            for (String userId : userIdList) {
                for (int i = 0; i < count; i++) {
                    CouponCode couponCode = new CouponCode();
                    couponCode.setId(UUIDGenerator.getUUID());
                    couponCode.setCouponCode(DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.getRandomStr());
                    couponCode.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    couponCode.setAddTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    couponCode.setCouponId(coupon.getId());
                    couponCode.setUserId(userId);
                    couponCode.setStatus(0);
                    couponCode.setType(coupon.getType());
                    couponCode.setUseTimeEnd(useEnd);
                    couponCode.setCouponName(coupon.getName());
                    if (coupon.getUseTimeType() == 1) {
                        couponCode.setUseTimeStart(coupon.getUseTimeStart());
                    } else {
                        couponCode.setUseTimeStart(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    }
                    couponCode.setSenderName(senderName);
                    couponCodeRepository.saveAndFlush(couponCode);
                    //推送发券成功模板 TODO
                    //保存发券成功记录
                    SendCouponRecord sendCouponRecord = new SendCouponRecord();
                    sendCouponRecord.setId(UUIDGenerator.getUUID());
                    sendCouponRecord.setCouponId(coupon.getId());
                    sendCouponRecord.setUserId(userId);
                    sendCouponRecord.setSendTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    sendCouponRecord.setStatus(0);
                    sendCouponRecord.setCount(count);
                    sendCouponRecord.setCouponName(coupon.getName());
                    sendCouponRecord.setSenderName(senderName);
                    sendCouponRecordRepository.saveAndFlush(sendCouponRecord);
                }
            }
        } else {
            //根据优惠券使用期限和券id查找对应的code，并将code锁定
            for (String userId : userIdList) {
                   /* for (int i = 0; i < count; i++) {
                        List<CouponCode> couponCodeList = couponCodeRepository.queryByCouponIdAndStatus(coupon.getId());
                        CouponCode couponCode = couponCodeList.get(0);
                        System.out.println(userId);
                        System.out.println(couponCode.getId());
                        if (coupon.getUseTimeType() == 1) {
                            couponCodeRepository.addUserCouponCode1(couponCode.getId(), userId, DateUtils.dateToString(date, DateUtils.TIMESTAMP), senderName, useEnd,coupon.getUseTimeStart());
                        } else {add
                            couponCodeRepository.addUserCouponCode1(couponCode.getId(), userId, DateUtils.dateToString(date, DateUtils.TIMESTAMP), senderName, useEnd,DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                        }
                    }*/
                for (int i = 0; i < count; i++) {
                    List<CouponCode> couponCodeList = couponCodeRepository.queryByCouponIdAndStatus(coupon.getId());
                    addMemberCouponCode(couponCodeList, useEnd, userId, senderName, coupon, 0);
                }
                //推送发券成功模板 TODO
                //保存发券成功记录
                SendCouponRecord sendCouponRecord = new SendCouponRecord();
                sendCouponRecord.setId(UUIDGenerator.getUUID());
                sendCouponRecord.setCouponId(coupon.getId());
                sendCouponRecord.setUserId(userId);
                sendCouponRecord.setSendTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                sendCouponRecord.setStatus(0);
                sendCouponRecord.setCount(count);
                sendCouponRecord.setCouponName(coupon.getName());
                sendCouponRecord.setSenderName(senderName);
                sendCouponRecordRepository.saveAndFlush(sendCouponRecord);
            }
        }
        return "发券成功";
    }

    private boolean addMemberCouponCode(List<CouponCode> codeList, String useEnd, String userId, String senderName, Coupon coupon, Integer count) {
        Date date = new Date();
        if (codeList.size() < 1) {
            return false;
        } else {
            Random rand = new Random();
            int randNum = rand.nextInt(codeList.size());
            CouponCode couponCode = codeList.get(randNum);
            int ret;
            if (coupon.getUseTimeType() == 1) {
                ret = couponCodeRepository.addUserCouponCode(couponCode.getId(), userId, DateUtils.dateToString(date, DateUtils.TIMESTAMP), senderName, useEnd, null, coupon.getUseTimeStart());
            } else {
                ret = couponCodeRepository.addUserCouponCode(couponCode.getId(), userId, DateUtils.dateToString(date, DateUtils.TIMESTAMP), senderName, useEnd, null, DateUtils.dateToString(date, DateUtils.TIMESTAMP));
            }
            if (ret == 0) {
                codeList.remove(randNum);
                return addMemberCouponCode(codeList, useEnd, userId, senderName, coupon, count);
            } else {
                couponRepository.updateRemainTotal(coupon.getId(), count);
            }
            return true;
        }
    }

    public CouponDTO queryDetailsById(String couponId) {
        Coupon coupon = couponRepository.findByCouponId(couponId);

        List<String> storeIdList = new LinkedList<>();
        List<StoreCoupon> storeCoupons = storeCouponRepository.findByCouponId(couponId);
        for (StoreCoupon storeCoupon : storeCoupons) {
            storeIdList.add(storeCoupon.getStoreId());
        }
        CouponDTO couponDTO = new CouponDTO();
        BeanUtils.copyProperties(coupon, couponDTO);
        couponDTO.setStoreIdList(storeIdList);

        //塞图片
        IdDTO idDTO = new IdDTO();
        idDTO.setForeignKeyId(coupon.getId());
        ImageDTO imageDTO = restTemplate.postForObject("http://quanquan-resource/image/image_query", idDTO, ImageDTO.class);
        for (Image image : imageDTO.getImageDTOs()) {
            if (image.getLogo()) {
                coupon.setImage(image.getImageAddress());
                couponRepository.saveAndFlush(coupon);
                couponDTO.setImage(image.getImageAddress());
                couponDTO.setImageId(image.getId());
            } else {
                coupon.setPicture(image.getImageAddress());
                couponRepository.saveAndFlush(coupon);
                couponDTO.setPictureId(image.getId());
                couponDTO.setPicture(image.getImageAddress());

            }
        }
        return couponDTO;
    }


    /**
     * 停车券核销记录
     *
     * @param requestBody
     * @return
     */
    public PageDTO<CouponCodeDTO> parkingRecord(CouponCodeRequest requestBody) {
        //分页
        Integer page = null == requestBody.getPage() ? 0 : requestBody.getPage();
        Integer size = null == requestBody.getSize() ? 10 : requestBody.getSize();
        //优惠券创建时间区间
        String fromDate = requestBody.getFromDate();
        String toDate = requestBody.getToDate();
        Integer type = requestBody.getType();
        String couponName = requestBody.getCouponName();
        //排序状态
        Sort sort = new Sort(Sort.Direction.DESC, "useTime");
        //搜索关键词
        String keyword = requestBody.getKeyword();
        Pageable pageable = PageRequest.of(page, size, sort);
        Page<CouponCode> paged = couponCodeRepository.findAll((Specification<CouponCode>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            // 创建具体查询条件
            if (null != type) {
                predicates.add(criteriaBuilder.equal(root.get("type").as(Integer.class), type));
            }
            if (StringUtil.isNotEmpty(fromDate)) {
                Date startOfDay = DateUtils.getStartOfDay(DateUtils.strToDate(fromDate, DateUtils.DATE));
                predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("useTime").as(Date.class), startOfDay));
            }
            if (StringUtil.isNotEmpty(toDate)) {
                Date endOfDay = DateUtils.getEndOfDay(DateUtils.strToDate(toDate, DateUtils.DATE));
                predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("useTime").as(Date.class), endOfDay));
            }
            // 创建具体查询条件
            if (StringUtil.isNotEmpty(couponName)) {
                Predicate p = criteriaBuilder.equal(root.get("couponId").as(String.class), couponName);
                predicates.add(p);
            }
            if (StringUtil.isNotEmpty(keyword)) {
                IdDTO idDTO = new IdDTO();
                idDTO.setKeyWord(keyword);
                UserInfoDTO userInfoDTO = restTemplate.postForObject("http://QUANQUAN-USER/user/query_keyword", idDTO, UserInfoDTO.class);
                if (userInfoDTO != null) {
                    List<DTO.user.UserDTO> users = userInfoDTO.getUserDTOS();
                    if (users.size() > 0) {
                        DTO.user.UserDTO userDTO = users.get(0);
                        predicates.add(criteriaBuilder.equal(root.get("userId").as(String.class), userDTO.getId()));
                    }

                } else {
                    Predicate p = criteriaBuilder.like(root.get("couponCode").as(String.class), "%" + keyword + "%");
                    Predicate p1 = criteriaBuilder.or(criteriaBuilder.like(root.get("carNumber").as(String.class), "%" + keyword + "%"), p);
                    predicates.add(p1);
                }

            }
            predicates.add(criteriaBuilder.equal(root.get("status"), 1));
            predicates.add(criteriaBuilder.equal(root.get("type"), 3));
            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        }, pageable);
        List<CouponCode> couponCodes = paged.getContent();
        List<String> userIds = couponCodes.stream().filter(distinctByKey(CouponCode::getUserId)).map(CouponCode::getUserId).collect(Collectors.toList());
        List<CouponCodeDTO> couponCodeDTOS = new LinkedList<>();
        for (CouponCode couponCode : couponCodes) {
            Coupon coupon = couponRepository.findByCouponId(couponCode.getCouponId());
            CouponCodeDTO couponCodeDTO = new CouponCodeDTO();
            BeanUtils.copyProperties(couponCode, couponCodeDTO);
            couponCodeDTO.setCouponName(coupon.getName());
            couponCodeDTO.setUseTimeStart(coupon.getUseTimeStart());
            couponCodeDTOS.add(couponCodeDTO);

        }
        IdDTO idDTO = new IdDTO();
        idDTO.setForeignKeyIds(userIds);

        UserInfoDTO userInfoDTO = restTemplate.postForObject("http://QUANQUAN-USER/user/query_by_id_list", idDTO, UserInfoDTO.class);
        assert userInfoDTO != null;
        List<DTO.user.UserDTO> userDTOS = userInfoDTO.getUserDTOS();
        for (CouponCodeDTO couponCodeDTO : couponCodeDTOS) {
            for (DTO.user.UserDTO userDTO : userDTOS) {
                if (couponCodeDTO.getUserId().equals(userDTO.getId())) {
                    couponCodeDTO.setUseName(userDTO.getMemberName());
                    couponCodeDTO.setUseMemberCard(userDTO.getMemberCardNum());
                    couponCodeDTO.setPhone(userDTO.getPhone());
                }
            }
        }
        PageDTO<CouponCodeDTO> dto = new PageDTO<>();
        dto.setTotal(paged.getTotalElements());
        dto.setList(couponCodeDTOS);
        dto.setPage(page);
        dto.setPageSize(size);
        dto.setKeyword(requestBody.getKeyword());
        dto.setTotalPage(paged.getTotalPages());
        dto.setFromDate(fromDate);
        dto.setToDate(toDate);
        dto.setCouponName(couponName);
        return dto;
    }


    /**
     * 后台查看券详情
     *
     * @param id
     * @return
     */
    public CouponDTO queryByIdManage(String id) {
        Coupon coupon = couponRepository.findByCouponId(id);
        CouponDTO couponDTO = new CouponDTO();
        BeanUtils.copyProperties(coupon, couponDTO);
        if (coupon.getBindType() != null) {
            if (coupon.getBindType() == 1) {
                //传入storeId用于回显
                List<String> storeIdList = new LinkedList<>();
                List<StoreCoupon> storeCoupons = storeCouponRepository.queryByIdManage(coupon.getId());
                for (StoreCoupon storeCoupon : storeCoupons) {
                    storeIdList.add(storeCoupon.getStoreId());
                }
                couponDTO.setStoreIdList(storeIdList);
            } else {
                //传入业态id用于回显
                List<String> commercialIdList = new LinkedList<>();
                List<CouponCommercial> couponCommercials = couponCommercialRepository.findByCouponIdAndStatus(coupon.getId());
                for (CouponCommercial couponCommercial : couponCommercials) {
                    commercialIdList.add(couponCommercial.getCommercialId());
                }
                couponDTO.setCommercialIdList(commercialIdList);
            }
        }
        if (Integer.valueOf(1).equals(coupon.getSumType())) {
            couponDTO.setRemainTotal("充足");
        } else {
            couponDTO.setRemainTotal(coupon.getRemainTotal().toString());
        }
        //塞图片
        IdDTO idDTO = new IdDTO();
        idDTO.setForeignKeyId(coupon.getId());
        ImageDTO imageDTO = restTemplate.postForObject("http://quanquan-resource/image/image_query", idDTO, ImageDTO.class);
        for (Image image : imageDTO.getImageDTOs()) {
            if (image.getLogo()) {
                coupon.setImage(image.getImageAddress());
                couponRepository.saveAndFlush(coupon);
                couponDTO.setImage(image.getImageAddress());
                couponDTO.setImageId(image.getId());
            } else {
                coupon.setPicture(image.getImageAddress());
                couponRepository.saveAndFlush(coupon);
                couponDTO.setPicture(image.getImageAddress());
                couponDTO.setPictureId(image.getId());
            }
        }
        return couponDTO;
    }


    /**
     * 优惠券发放记录
     *
     * @param requestBody
     * @return
     */
    public PageDTO<CouponCodeDTO> sendRecord(CouponCodeRequest requestBody) {
        //分页
        Integer page = null == requestBody.getPage() ? 0 : requestBody.getPage();
        Integer size = null == requestBody.getSize() ? 10 : requestBody.getSize();
        //优惠券创建时间区间
        String fromDate = requestBody.getFromDate();
        String toDate = requestBody.getToDate();
        Integer type = requestBody.getType();
        String couponName = requestBody.getCouponName();
        //排序状态
        Sort sort = new Sort(Sort.Direction.DESC, "addTime");
        //搜索关键词
        String keyword = requestBody.getKeyword();
        Pageable pageable = PageRequest.of(page, size, sort);
        Page<CouponCode> paged = couponCodeRepository.findAll((Specification<CouponCode>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            // 创建具体查询条件
            if (null != type) {
                predicates.add(criteriaBuilder.equal(root.get("type").as(Integer.class), type));
            }
            if (StringUtil.isNotEmpty(fromDate)) {
                Date startOfDay = DateUtils.getStartOfDay(DateUtils.strToDate(fromDate, DateUtils.DATE));
                predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("addTime").as(Date.class), startOfDay));
            }
            if (StringUtil.isNotEmpty(toDate)) {
                Date endOfDay = DateUtils.getEndOfDay(DateUtils.strToDate(toDate, DateUtils.DATE));
                predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("addTime").as(Date.class), endOfDay));
            }
            // 创建具体查询条件
            if (StringUtil.isNotEmpty(couponName)) {
                Predicate p = criteriaBuilder.equal(root.get("couponId").as(String.class), couponName);
                predicates.add(p);
            }
            if (StringUtil.isNotEmpty(keyword)) {
                IdDTO idDTO = new IdDTO();
                idDTO.setKeyWord(keyword);
                UserInfoDTO userInfoDTO = restTemplate.postForObject("http://QUANQUAN-USER/user/query_keyword", idDTO, UserInfoDTO.class);
                if (userInfoDTO != null) {
                    List<DTO.user.UserDTO> users = userInfoDTO.getUserDTOS();
                    if (users.size() > 0) {
                        DTO.user.UserDTO userDTO = users.get(0);
                        predicates.add(criteriaBuilder.equal(root.get("userId").as(String.class), userDTO.getId()));
                    }
                } else {
                    Predicate p = criteriaBuilder.like(root.get("couponCode").as(String.class), "%" + keyword + "%");
                    Predicate p1 = criteriaBuilder.or(criteriaBuilder.like(root.get("couponName").as(String.class), "%" + keyword + "%"), p);
                    Predicate p2 = criteriaBuilder.or(criteriaBuilder.like(root.get("senderName").as(String.class), "%" + keyword + "%"), p1);
                    predicates.add(p2);
                }
            }
            predicates.add(criteriaBuilder.notEqual(root.get("status"), -1));
            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        }, pageable);
        List<CouponCode> couponCodes = paged.getContent();
        List<String> userIds = couponCodes.stream().filter(distinctByKey(CouponCode::getUserId)).map(CouponCode::getUserId).collect(Collectors.toList());
        List<CouponCodeDTO> couponCodeDTOS = new LinkedList<>();
        for (CouponCode couponCode : couponCodes) {
            Coupon coupon = couponRepository.findByCouponId(couponCode.getCouponId());
            CouponCodeDTO couponCodeDTO = new CouponCodeDTO();
            BeanUtils.copyProperties(couponCode, couponCodeDTO);
            couponCodeDTO.setCouponName(coupon.getName());
            couponCodeDTO.setUseTimeStart(coupon.getUseTimeStart());
            couponCodeDTOS.add(couponCodeDTO);

        }
        IdDTO idDTO = new IdDTO();
        idDTO.setForeignKeyIds(userIds);

        UserInfoDTO userInfoDTO = restTemplate.postForObject("http://QUANQUAN-USER/user/query_by_id_list", idDTO, UserInfoDTO.class);
        assert userInfoDTO != null;
        List<DTO.user.UserDTO> userDTOS = userInfoDTO.getUserDTOS();
        for (CouponCodeDTO couponCodeDTO : couponCodeDTOS) {
            for (DTO.user.UserDTO userDTO : userDTOS) {
                if (couponCodeDTO.getUserId().equals(userDTO.getId())) {
                    couponCodeDTO.setUseName(userDTO.getMemberName());
                    couponCodeDTO.setUseMemberCard(userDTO.getMemberCardNum());
                    couponCodeDTO.setPhone(userDTO.getPhone());
                }
            }
        }
        PageDTO<CouponCodeDTO> dto = new PageDTO<>();
        dto.setTotal(paged.getTotalElements());
        dto.setList(couponCodeDTOS);
        dto.setPage(page);
        dto.setPageSize(size);
        dto.setKeyword(requestBody.getKeyword());
        dto.setTotalPage(paged.getTotalPages());
        dto.setFromDate(fromDate);
        dto.setToDate(toDate);
        dto.setCouponName(couponName);
        return dto;
    }

    /**
     * 优惠券获取\使用总数
     *
     * @return
     */
    public Map<String, Integer> couponCount() {
        List<CouponCode> getCoupon = couponCodeRepository.findGetCoupon(1);
        List<CouponCode> useCoupon = couponCodeRepository.findUseCoupon(1);
        List<CouponCode> getParkingCoupon = couponCodeRepository.findGetCoupon(3);
        List<CouponCode> useParkingCoupon = couponCodeRepository.findUseCoupon(3);
        Map<String, Integer> map = new HashMap<>();
        map.put("getCouponCount", getCoupon.size());
        map.put("useCouponCount", useCoupon.size());
        map.put("getParkingCoupon", getParkingCoupon.size());
        map.put("useParkingCoupon", useParkingCoupon.size());
        return map;
    }

    /**
     * 获取未过期的优惠券或停车券
     *
     * @return
     */
    public List<CouponDTO> findAlls(Integer type) {
        List<CouponDTO> couponDTOList = new LinkedList<>();
        List<Coupon> couponList = couponRepository.findAlls(type);
        for (Coupon coupon : couponList) {
            CouponDTO couponDTO = new CouponDTO();
            BeanUtils.copyProperties(coupon, couponDTO);
            couponDTOList.add(couponDTO);
        }
        return couponDTOList;
    }

    /**
     * 获取未过期的优惠券或停车券
     *
     * @return
     */
    public List<CouponDTO> findAllss(Integer type) {
        List<CouponDTO> couponDTOList = new LinkedList<>();
        List<Coupon> couponList = couponRepository.findAllss(type);
        for (Coupon coupon : couponList) {
            CouponDTO couponDTO = new CouponDTO();
            BeanUtils.copyProperties(coupon, couponDTO);
            couponDTOList.add(couponDTO);
        }
        return couponDTOList;
    }


    /**
     * 判断优惠
     *
     * @param couponId
     * @return
     */
    public Boolean checkCouponStatus(String couponId) {
        Coupon coupon = couponRepository.findByIdAndStatus(couponId);
        if (coupon == null) {
            return false;
        } else {
            return true;
        }
    }


    /**
     * 扣除库存
     *
     * @param shoppingKillnum
     * @param couponId
     * @return
     */
    public String deductInventory(Integer shoppingKillnum, String couponId) {
        Date date = new Date();
        Coupon coupon = couponRepository.findKillAll(couponId);
        Integer sumType = coupon.getSumType();
        if (sumType == 0) {
            Integer remainTotal = coupon.getRemainTotal();
            coupon.setShoppingKillNum(shoppingKillnum);
            Integer i = remainTotal - shoppingKillnum;
            if (i < 0) {
                return null;
            }
            coupon.setRemainTotal(i);
            couponRepository.save(coupon);
        }
        return "库存扣除成功";

    }


    public String completionInventory(Integer shoppingKillnum, String couponId) {
        System.out.println(couponId);
        Coupon coupon = couponRepository.findByIdAndStatus(couponId);
        System.out.println("coupon :" + coupon);
        Integer sumType = coupon.getSumType();
        if (sumType == 0) {
            Integer remainTotal = coupon.getRemainTotal();
            coupon.setShoppingKillNum(shoppingKillnum);
            Integer i = remainTotal + shoppingKillnum;
            if (i < 0) {
                return null;
            }
            coupon.setRemainTotal(i);
            couponRepository.save(coupon);
        }
        return "库存增补成功";

    }

    /**
     * 给商户充值停车券
     *
     * @return
     */
    public String sendCouponToStore(CouponRequest request) {
        Date date = new Date();
        Coupon coupon = couponRepository.findByCouponId(request.getId());
        if (coupon == null) {
            return "没有对应商品";
        }
        //如果前端不传值，默认发一张
        Integer count = request.getCount() == null ? 1 : request.getCount();
        Date now = new Date();
        //根据优惠券使用期限和券id查找对应的code，并将code锁定
        /*String useEnd = null;
        if (coupon.getUseTimeType() == 1) {
            useEnd = coupon.getUseTimeEnd();
        }
        if (coupon.getUseTimeType() == 2) {
            useEnd = DateUtils.dateToString(DateUtils.getDateAfterHour(coupon.getUseTimeHour()), DateUtils.TIMESTAMP);
        }
        if (coupon.getUseTimeType() == 3) {
            useEnd = DateUtils.dateToString(DateUtils.getEndOfDay(now), DateUtils.TIMESTAMP);
        }*/
        for (int i = 0; i < count; i++) {
            CouponCode couponCode = new CouponCode();
            couponCode.setId(UUIDGenerator.getUUID());
            couponCode.setCouponCode(DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.getRandomStr());
            couponCode.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
            couponCode.setAddTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
            couponCode.setCouponId(coupon.getId());
            couponCode.setStoreId(request.getStoreId());
            couponCode.setStatus(-1);
            couponCode.setType(coupon.getType());
            couponCode.setCouponName(coupon.getName());
            couponCode.setUseTimeStart(coupon.getUseTimeStart());
            couponCodeRepository.saveAndFlush(couponCode);
        }
        return "发券成功";
    }

    /**
     * 商户给用户发停车券
     *
     * @return
     */
    public String storeSendCouponToUser(CouponRequest request) {
        Date date = new Date();
        //在保证之前的代码可用的情况下，如果传入单个userId放入集合中
        List<String> userIdList = new LinkedList<>();
        if (request.getUserIdList() == null) {
            userIdList.add(request.getUserId());
        } else {
            userIdList = request.getUserIdList();
        }
        Coupon coupon = couponRepository.findByCouponId(request.getId());
        if (coupon == null) {
            return "没有对应商品";
        }
        String senderName;
        Integer sendRequestType = request.getSendRequestType() == null ? 1 : request.getSendRequestType();
        if (sendRequestType == 1) {
            senderName = "系统";
        } else {
            senderName = request.getSenderName();
        }
        //如果前端不传值，默认发一张
        Integer count = request.getCount() == null ? 1 : request.getCount();
        Date now = new Date();
        //根据优惠券使用期限和券id查找对应的code，并将code锁定
        String useEnd = null;
        if (coupon.getUseTimeType() == 1) {
            useEnd = coupon.getUseTimeEnd();
        }
        if (coupon.getUseTimeType() == 2) {
            useEnd = DateUtils.dateToString(DateUtils.getDateAfterHour(coupon.getUseTimeHour()), DateUtils.TIMESTAMP);
        }
        if (coupon.getUseTimeType() == 3) {
            useEnd = DateUtils.dateToString(DateUtils.getEndOfDay(now), DateUtils.TIMESTAMP);
        }
        // 查找商户下剩余停车券券量
        List<CouponCode> couponCodeList1 = couponCodeRepository.queryByCouponIdAndStoreId(request.getId(), request.getStoreId());
        if (couponCodeList1.size() >= userIdList.size() * count) {
            //根据优惠券使用期限和券id查找对应的code，并将code锁定
            for (String userId : userIdList) {
                for (int i = 0; i < count; i++) {
                    List<CouponCode> couponCodeList = couponCodeRepository.queryByCouponIdAndStatus(coupon.getId());
                    CouponCode couponCode = couponCodeList.get(0);
                    if (coupon.getUseTimeType() == 1) {
                        couponCodeRepository.addUserCouponCode2(couponCode.getId(), userId, DateUtils.dateToString(date, DateUtils.TIMESTAMP), senderName, useEnd, coupon.getUseTimeStart());
                    } else {
                        couponCodeRepository.addUserCouponCode2(couponCode.getId(), userId, DateUtils.dateToString(date, DateUtils.TIMESTAMP), senderName, useEnd, DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    }
                }
            }
        } else {
            return "商品数量不足";
        }
        return "发券成功";
    }


    /**
     * 通过id集合查找券
     *
     * @param foreignKeyIds
     * @return
     */
    public List<DTO.coupon.CouponDTO> queryByIdList(List<String> foreignKeyIds) {
        List<Coupon> couponList = couponRepository.findAllById(foreignKeyIds);
        List<DTO.coupon.CouponDTO> couponDTOList = new ArrayList<>();
        for (Coupon coupon : couponList) {
            DTO.coupon.CouponDTO couponDTO = new DTO.coupon.CouponDTO();
            //通过映射关系来赋值 //TODO 断点看一下
            BeanUtils.copyProperties(coupon, couponDTO);

            couponDTOList.add(couponDTO);
        }
        return couponDTOList;
    }

    /**
     * 更新券
     *
     * @param userId
     * @param couponId
     * @param count
     * @return
     */
    public boolean updateCouponCodeStatus(String userId, String couponId, Integer count) {
        List<CouponCode> couponCodeList = couponCodeRepository.findByCouponIdAndUserIdByCount(couponId, userId, count);
        for (CouponCode couponCode : couponCodeList) {
            couponCode.setStatus(0);
            couponCodeRepository.saveAndFlush(couponCode);
        }
        return true;
    }

    /**
     * 通过券id核销优惠券
     *
     * @param codeId
     * @return
     */
    public boolean cancelByCodeId(String codeId) {
        CouponCode couponCode = couponCodeRepository.queryById(codeId);
        if (couponCode == null || couponCode.getStatus() == 1) {
            return false;
        }
        couponCode.setStatus(1);
        couponCode.setUseTime(DateUtils.currentDate());
        couponCodeRepository.saveAndFlush(couponCode);
        return true;
    }
}
